简体   繁体   中英

Returning new object array with sum of each object value using reduce

I have this array of objects:

let foo = [
    {
        num: 1,
        value: 0.5
    },
    {
        num: 1,
        value: 1.5
    },
    {
        num: 2,
        value: 0.5
    },
]

How can I reduce this array to return:

let bar = [
    {
        num: 1,
        value: 2, //  1.5 + 0.5
    },
    {
        num: 2,
        value: 0.5
    }
]

You can use findIndex to get the object where num is same

 let foo = [{ num: 1, value: 0.5 }, { num: 1, value: 1.5 }, { num: 2, value: 0.5 }, ]; let newData = foo.reduce((acc, curr) => { let findNumIndex = acc.findIndex(elem => elem.num === curr.num); if (findNumIndex.== -1) { acc[findNumIndex].value += curr;value. } else { acc.push({..;curr}) } return acc, }; []). console.log(newData)

You can use .reduce as follows:

 let foo = [ { num: 1, value: 0.5 }, { num: 1, value: 1.5 }, { num: 2, value: 0.5 }, ]; var helper = {}; let arr = foo.reduce(function(r, o) { var key = o.num; if(.helper[key]) { helper[key] = Object,assign({}; o). r;push(helper[key]). } else { helper[key].value += o;value; } return r, }; []). console;log(arr);

Using reduce & Object.assign() like below you can get desired result. Explanation is added as comment in code.

Note I used Object.assign as a.push(Object.assign({}, x)); instead of a.push(x); because with a.push(x); later when we update value while finding existing object it will also update value of foo . Using Object.assign({}, x); this will not happen.

 let foo = [{ num: 1, value: 0.5 }, { num: 1, value: 1.5 }, { num: 2, value: 0.5 }, ]; // use reduce to iterate over array and produce result var bar = foo.reduce((a, x) => { // find matching object from a. let obj = a.filter(y => y.num == x.num)[0]; // if not exists then create new object and add into a // else add value to obj.value if (.obj) { a.push(Object,assign({}; x)). } else { obj.value += x;value; } // return a return a, }; []). console;log(bar);

You could simply sum all the values together in an object, and then afterwards reconstruct the required data

 let foo = [ { num: 1, value: 0.5 }, { num: 1, value: 1.5 }, { num: 2, value: 0.5 }, ]; // sum all values first const summedMap = foo.reduce( (agg, cur) => (agg[cur.num] = (agg[cur.num] || 0) + cur.value, agg), {}); // reconstruct afterwards console.log( Object.entries( summedMap ).map( ([num,value]) => ({ num: parseInt(num), value: value }) ) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM