Aggregating object values of JavaScript arrays?

前端 未结 2 421
时光取名叫无心
时光取名叫无心 2020-12-21 04:12

In JavaScript, given n number of arrays as input in this format: (n=2)

array1:
[{x: 1, y: 5},{x: 2, y: 3},{x: 3, y: 6}]

array2:
[{x: 1, y: 2},{x: 2, y: 6},{         


        
2条回答
  •  盖世英雄少女心
    2020-12-21 04:37

    Benchmark Example

    Note that the mixed code is faster followed by loops followed by native/underscore.

    function createOutput(arr1, arr2, arr3 /*, ... */) {
        return Array.prototype.reduce.call(arguments, function (prev, curr) {
            return prev.map(function(val, index) {
                return {
                    x: val.x,
                    y: val.y + curr[index].y
                }
            });
        });
    }
    

    Assumes arrays are sorted and contain all values of x in order 1..n with no gaps.

    Kind of requires ES5. This can be swapped out for _ which gives this kind of functionality in a cross browser manner.

    With underscore it is

    function createOutput() {
        return _.reduce(arguments, function (memo, arr) {
            return _.map(memo, function(val, index) {
                return { x: val.x, y: val.y + arr[index].y };
            });
        });
    }
    

提交回复
热议问题