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

前端 未结 9 2495
醉梦人生
醉梦人生 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:18

    Try this, it should help

    var arr1 = [
        { name: 'besart', value: 12 },
        { name: 'astrit', value: 10 },
        { name: 'astrit', value: 10 },
        { name: 'besar', value: 18 },
        { name: 'besar', value: 3 },
        { name: 'astrit', value: 3 },
        { name: 'besart', value: 3 },
        { name: 'besart', value: 10 },
        { name: 'besar', value: 0 },
    ];
    
    var arr2 = [];
    var emri = "";
    var value = 0;
    for(var i = 0;i

    Below is another solution that uses only one loop (while loop):

     var arr2 = [];
        var emri = "";
        var value = 0;
        var i=1;
        var j=0;
    
    while(arr1.length != 0){
            emri = arr1[0].name;
            if(emri == arr1[i].name){
                value+=arr1[i].value;
                arr1.splice(i,1);
                i--;
            }
            i++;
            if(i==arr1.length){
                value+=arr1[0].value;
                i=1;
                arr2[j]={name:emri,value:value};
                j++;
                value=0;
                arr1.splice(0,1);
            }
        }
    

提交回复
热议问题