0

I have a javascript array that looks like this

var array = [{
        id: 1,
        quantity: 2
    },
    {
        id: 2,
        quantity: 1
    },
    {
        id: 1,
        quantity: 5
    }
]

In the above code snippet two objects has same id id:1. If id of two or more objects are same in the array. I want them to be converted into single object and the quantity property of all the object with that particular id id:1 gets accumulated. So the response array should look like this.

var resArray = [{
        id: 1,
        quantity: 7
    },
    {
        id: 2,
        quantity: 1
    }
]
1

1 Answer 1

2

Using Array.reduce, you can group the array by id key value and can sum the quantities of same id.

const array = [{
    id: 1,
    quantity: 2
  },
  {
    id: 2,
    quantity: 1
  },
  {
    id: 1,
    quantity: 5
  }
];

const reducedArr = array.reduce((acc, cur) => {
  acc[cur.id] ? acc[cur.id].quantity += cur.quantity : acc[cur.id] = cur;
  return acc;
}, {});

const output = Object.values(reducedArr);
console.log(output);

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

1 Comment

thanks a lot. well that's perfect. though i was wondering if there is anyway possible to directly recuce the array into result array(acc being an empty array instead of empty object).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.