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

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

    You could use a hash table for the grouping by key.

    var array = [{ 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}],
        grouped = [];
    
    array.forEach(function (o) {
        if (!this[o.key]) {
            this[o.key] = { key: o.key, val: 0 };
            grouped.push(this[o.key]);
        }
        this[o.key].val += o.val;
    }, Object.create(null));
    
    console.log(grouped);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    Another approach is to collect all key/value pairs in a Map and format the final array with Array.from and a callback for the objects.

    var array = [{ 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 }],
        grouped = Array.from(
            array.reduce((m, { key, val }) => m.set(key, (m.get(key) || 0) + val), new Map),
            ([key, val]) => ({ key, val })
        );
    
    console.log(grouped);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题