Sum javascript object propertyA values with same object propertyB in array of objects

前端 未结 9 2494
醉梦人生
醉梦人生 2020-11-22 04:48

How would one take a javascript array of objects such as:

my objArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:42},
{key:Mon Sep 24 2013 00:00:00 GMT-04         


        
9条回答
  •  忘了有多久
    2020-11-22 05:22

    Recently l needed a similar implementation and l used a similar solution offered by some guy that used reduce function. Few days later i wanted to implement something similar by myself and here is the result.

    const users = [
            { id: 1, name: 'ernest', spent: 40 }, 
            { id: 2, name: 'ernest', spent: 40 },
            { id: 3, name: 'astrit', spent: 22 },
            { id: 4, name: 'astrit', spent: 2956 },
            { id: 5, name: 'astrit', spent: 22 }, 
            { id: 6, name: 'besart', spent: 40 }, 
            { id: 7, name: 'besart', spent: 100}, 
            { id: 8, name: 'besart', spent: 4000 }
        ];
    
            const sum = [];
    
            users.forEach(el => {
                if(sum.length === 0){
                    delete el.id;
                    sum.push(el);
                }    
                else
                {
                    const get = () => {
                        for(let i = 0; i < sum.length; i++){
                            if(sum[i].name === el.name ){
                                return { stat: true, id: i };
                            }
                        }
                    }
    
                    let i = get();
                    if(i){
                        sum[i.id].spent += el.spent;
                    }
                    else
                    {
                        delete el.id;
                        sum.push(el);
                    }
                }
            });
    
            console.log(sum);
    

    Output:

    [ { name: 'ernest', spent: 80 }, { name: 'astrit', spent: 3000 }, { name: 'besart', spent: 4140 } ]
    

提交回复
热议问题