skip to Main Content

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 }
]

2

Answers


  1. 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;
        }, {})));
    Login or Signup to reply.
  2. 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)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search