Home > Enterprise >  Remove duplicate objects based on the same key from array and add their value to the object that is
Remove duplicate objects based on the same key from array and add their value to the object that is

Time:12-09

Consider the following array of objects in javascript

const array = [
  { 10205: 2 },
  { 10207: 3 },
  { 10205: 2 },
  { 10207: 1 }
]

I would like to have it converted to

array = [
  { 10205: 4 },
  { 10207: 4 }
]

CodePudding user response:

Please use reduce function.

    const array = [
      { 10205: 2 },
      { 10207: 3 },
      { 10205: 2 },
      { 10207: 1 }
    ]
    
    console.log(Object.values(array.reduce((acc, el)=>{
        Object.keys(el).map((key)=>{
            acc[key] = {
                [key]: (acc?.[key]?.[key] ?? 0)   el[key],
            }
        })
        return acc;
    }, {})));

CodePudding user response:

const array = [{ 10205: 2 }, { 10207: 3 }, { 10205: 2 }, { 10207: 1 }];

const newArray = [];
array.forEach((element) => {
  const elementKey = Object.keys(element)[0];
  const foundIndex = newArray.findIndex((_) => Object.keys(_)[0] === elementKey);
  if (foundIndex >= 0) {
    newArray[foundIndex] =
        {[elementKey]: newArray[foundIndex][elementKey]   element[elementKey]};
  } else newArray.push(element);
});
console.log(newArray)

  • Related