1

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
  • I recommend showing the code that you have tried so far as SO isn't a code writing service. Commented Dec 8, 2022 at 22:04
  • There are lots of duplicates on "grouping". Like this one. Commented Dec 8, 2022 at 22:07

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.
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;
    }, {})));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.