Home > Software engineering >  Group values by a specific key in a nested array
Group values by a specific key in a nested array

Time:06-17

What would be the most efficient way to group items by the name key in a nested array/object?

The main array looks something like this here:

let arr = [
  {
    id: 123,
    compensatedItems: [
      {
        name: 'Random item 1',
        id: '123512',
        reason: 'missing_items',
      },
      {
        name: 'Random item 1',
        id: '123512',
        reason: 'missing_items',
      },
      {
        name: 'Random item 1',
        id: '123512',
        reason: 'missing_items',
      },
      {
        name: 'Another random item',
        id: '24122',
        reason: 'missing_items',
      },
      {
        name: 'Another random item',
        id: '24122',
        reason: 'missing_items',
      },
    ],
  },
  {
    id: 341,
    compensatedItems: [
      {
        name: 'Random item 1',
        id: '123512',
        reason: 'missing_items',
      },
      {
        name: 'Random item 1',
        id: '123512',
        reason: 'missing_items',
      },
      {
        name: 'Another random item',
        id: '24122',
        reason: 'missing_items',
      },
    ],
  },
];

Where you have a main array that has multiple objects, and each object has a compensatedItems array with additional objects in it.

I'd like to get the compensatedItems grouped by the name so that the end result would look something like

let res = [
  {
    name: 'Random item 1',
    id: '123512',
    reason: 'missing_items',
    count: 5,
  },
  {
    name: 'Another random item',
    id: '24122',
    reason: 'missing_items',
    count: 3,
  },
];

Its one of those days when nothing makes sense and having a hard time coming up with an efficient solution without looping 1000 times.

  • Related