Merge arrays in objects in array based on property I have the following code which takes an array that might have duplicate ids and will merge the items of those duplicate, and keep only one element per id which contains all the items of all elements with the same id.


array = [{
    id: 1,
    items: [1, 2, 3]
  },
  {
    id: 2,
    items: [1, 2]
  },
  {
    id: 1,
    items: [4]
  },
  {
    id: 3,
    items: [1]
  },
];

const mergeLines = (a) =&gt; {
  const processedIds = [];
  const finalResult = [];
  a.forEach((element) =&gt; {
    const elementId = element.id;
    if (processedIds.indexOf(elementId) === -1) {
      const occurences = a.filter((el) =&gt; el.id === elementId);
      if (occurences.length &gt; 1) {
        const allItems = occurences.reduce((acc, curr) =&gt; {
          acc = acc.concat(curr.items);
          return acc;
        }, []);
        element = { ...element,
          items: allItems
        };
        finalResult.push(element);
      } else {
        finalResult.push(element);
      }

      processedIds.push(elementId);
    }
  });
  return finalResult;
};

console.log(mergeLines(array));



I feel this code can be optimized much further to 0(n)
A short review;

This code looks incredibly complicated for what you want to achieve, sometimes a few for loops beat the functional approach
array is a global variable (not var or set or const), that is a bad thing
If a function is not inline, I would encourage you to use the function keyword
I am not sure mergeLines is a great name, perhaps mergeIds ?



array = [{
    id: 1,
    items: [1, 2, 3]
  },
  {
    id: 2,
    items: [1, 2]
  },
  {
    id: 1,
    items: [4]
  },
  {
    id: 3,
    items: [1]
  },
];

function mergeIds(list){
  const out = [];
  for(entry of list){
    const existingEntry = out.find(o =&gt; o.id === entry.id);
    if(existingEntry){
      existingEntry.items = existingEntry.items.concat(entry.items);
    } else {
      out.push(entry);
    }
  }
  
  return out;
}

console.log(mergeIds(array));