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

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

    Here is an alternative for you, but similar to that of Explosion Pills, reuses the original array rather than creating a new one or a different object. The sort may not be necessary and will slow things down a little, but it could be removed.

    Javascript

    function reduceMyObjArr(arr) {
        var temp = {},
            index;
    
        for (index = arr.length - 1; index >= 0; index -= 1) {
            key = arr[index].key;
            if (temp.hasOwnProperty(key)) {
                arr[temp[key]].val += arr[index].val;
                arr.splice(index, 1);
            } else {
                temp[key] = index;
            }
        }
    
        arr.sort(function (a, b) {
            if (a.key === b.key) {
                return 0;
            }
    
            if (a.key < b.key) {
                return -1;
            }
    
            return 1;
        });
    
        return arr;
    }
    
    var myObjArr = [{
        key: "Mon Sep 23 2013 00: 00: 00 GMT - 0400",
        val: 42
    }, {
        key: "Mon Sep 24 2013 00: 00: 00 GMT - 0400",
        val: 78
    }, {
        key: "Mon Sep 25 2013 00: 00: 00 GMT - 0400",
        val: 23
    }, {
        key: "Mon Sep 23 2013 00: 00: 00 GMT - 0400",
        val: 54
    }];
    
    reduceMyObjArr(myObjArr);
    
    console.log(myObjArr);
    

    jsFiddle

    And a jsperf that compares this (with and without the sort) against the accepted answer. You can improve the performance test by extending the data set.

提交回复
热议问题