-1

I have a array of objects, for exemple:

let arr = [
  {title:apple,quantity:2},
  {title:banana,quantity:3},
  {title:apple,quantity:5},
  {title:banana,quantity:7}
];

array containe many same objects, and i want recived array with uniqe object :

let result  = [
  {title:apple,quantity:7},
  {title:banana,quantity:10}
]

How can I do this?

Sapna Dorbi
  • 115
  • 2
  • 12
Braslik
  • 13
  • 1
  • 4
  • Wont this help - https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects – Mahesh_Loya Oct 31 '20 at 07:54

3 Answers3

0

This is done on a phone so may have some typos but the gist is there:

const resultObj = arr.reduce((acc,curr) =>{
acc[curr.title] = acc[curr.title]== undefined? curr.quantity: acc[curr.title] + curr.quantity
return acc
},{})

const resultArr = Object.entries(resultObj).map([key,value]=>({title:key,quantity:value}))
chantey
  • 4,252
  • 1
  • 35
  • 40
0

You can iterate over your array and filter out all the object with same title. Then use reduce to add all the quantity and return a new object. Code is below,

let newArr = [];

arr.forEach((currentObj) => {
    const alreadyExists = newArr.findIndex(item => currentObj.title === item.title) > -1;
    if(!alreadyExists) {    
        const filtered = arr.filter(item => item.title === currentObj.title);
        const newObject = filtered.reduce((acc, curr) => { return {...acc, quantity: acc.quantity += curr.quantity}}, {...currentObj, quantity: 0})
        newArr.push(newObject);
    }
})
console.log(newArr);
Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30
0

You could do that in "one line" using arrow function expressions but it won't be very readable unless you know what's happening inside:

let arr = [
  {title: "apple",quantity:2},
  {title: "banana",quantity:3},
  {title: "apple",quantity:5},
  {title: "banana",quantity:7}
];

let newArr = [...arr.reduce((acc, {title, quantity}) => 
   (acc.set(title, quantity + acc.get(title) || 0), acc), new Map())
].map(([title, quantity]) => ({title, quantity}));

console.log(newArr);

So basically the first part is the reduce method:

arr.reduce((acc, {title, quantity}) => 
   (acc.set(title, quantity + acc.get(title) || 0), acc), new Map())

That will returns a Map object, where each title is a key (e.g. "apple") and the quantity is the value of the key.

At this point you have to convert the Map object into an array again, and you do it using the spread syntax.

After you got an array back, you will have it in the following form:

[["apple", 7], ["banana", 10]]

But that is not what you want yet, not in this form, so you have to convert it using the array's map method:

<array>.map(([title, quantity]) => ({title, quantity}))

To keep it concise it uses the destructuring assignment

ZER0
  • 24,846
  • 5
  • 51
  • 54