聚合JavaScript数组的对象值? [英] Aggregating object values of JavaScript arrays?

查看:351
本文介绍了聚合JavaScript数组的对象值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,给定n个数组作为以下格式的输入:(n = 2)

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

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

如何轻松聚合Y值,并获取此结果数组:

  arrayOutput:
[{x:1,y:7},{x:2,y:9},{x:3,y:8}]

谢谢。

解决方案

更新:关于 x 值的额外评论及其在数组中的位置使以下无关紧要。



没有特别的技巧,你只需循环遍历数组并建立结果。它只不过是一个嵌套循环。如果您想要在广泛的JavaScript引擎中实现最高效率,请避免不必要的函数调用。



 函数sumYValues(arrays){
var outer,inner,array,entry,sum,result,x;

//使用第一个数组的副本创建我们的结果数组
result = [];
if(arrays.length> 0){
array = arrays [0];
for(inner = 0; inner< array.length; ++ inner){
entry = array [inner];
result [inner] = {x:entry.x,y:entry.y};
}

//添加剩余值
for(outer = 1; outer< arrays.length; ++ outer){
array = arrays [外];
//你可能想要一个assert这里验证result.length == array.length
for(inner = 0; inner< array.length; ++ inner){
entry =数组[内];
//你可能想要一个assert这里验证结果[内部] .x == entry.x
result [inner] .y + = entry.y;
}
}
}

返回结果;
}

这些循环从 0 (或 1 )到 array.length - 1 。你可以设定是否回退( array.length - 1 0 (或1))更快,多数下降到 0 一个。我以前假设是因为当我是一个新鲜的青年时,在C中(与 0 的比较比比较另一个变量更快),但是这个假设可能或可能在JavaScript中无效。






没有特定的快捷方式,您只需循环浏览数组,进行比较和建立你的结果。



如果 x 值在每个数组中都是唯一的,那么可能会更容易保留通过使用对象而不是数组来跟踪您的持续总和,并使用 x 值作为键,然后在完成后将其转换为数组。例如:

 函数sumYValues(arrays){
var outer,inner,ar,entry,sum,result,x ;

sum = {};
for(outer = 0; outer< arrays.length; ++ outer){
ar = arrays [outer]; (内部= 0;内部 {
entry = ar [inner];
sum [entry.x] =(sum [entry.x] || 0)+ entry.y;
}
}

result = [];
for(x in sum){
result.push({x:x,y:sum [x]});
}

返回结果;
}

上面大多只是演示使用 sum ,一个对象,作为 x => y 的映射,虽然它实现至少一些总结逻辑。



这一行可能需要一些解释:

  sum [entry.x] =(sum [entry.x] || 0)+ entry.y; 

如果 sum 没有条目因为 x 值, sum [entry.x] undefined ,这是一个falsey值。所以我们使用好奇的 || 操作符可以从 sum获得 x 的值>或 0 ,然后将当前条目的 y 添加到其中并存储结果。 p>

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},{x: 3, y: 2}]

How do I aggregate the Y-values easily and get this resulting array:

arrayOutput:
[{x: 1, y: 7},{x: 2, y: 9},{x: 3, y: 8}]

Thank you.

解决方案

Update: The additional comment about the x values and their positions in the arrays makes the below irrelevant.

There's no particular trick, you just loop through the arrays and build up your result. It's nothing more than a nested loop. If you're trying to be maximally efficient across a broad range of JavaScript engines, avoid unnecessary function calls.

Something along the lines of:

function sumYValues(arrays) {
    var outer, inner, array, entry, sum, result, x;

    // Create our result array with a copy of the first array
    result = [];
    if (arrays.length > 0) {
        array = arrays[0];
        for (inner = 0; inner < array.length; ++inner) {
            entry = array[inner];
            result[inner] = {x: entry.x, y: entry.y};
        }

        // Add in the remaining values
        for (outer = 1; outer < arrays.length; ++outer) {
            array = arrays[outer];
            // You might want an assert here verifying that result.length == array.length
            for (inner = 0; inner < array.length; ++inner) {
                entry = array[inner];
                // You might want an assert here verifying that result[inner].x == entry.x
                result[inner].y += entry.y;
            }
        }
    }

    return result;
}

Those loops count from 0 (or 1) to array.length - 1. You might profile whether going backwards (array.length - 1 to 0 (or 1)) is any faster, mostly the "down to 0" one. I used to assume it was because it was in C when I was a fresh-faced youth (comparisons to 0 are faster than comparisons to another variable), but that assumption may or may not be valid in JavaScript.


There's no particular shortcut, you just loop through the arrays, do your comparisons, and build up your result.

If the x values will be unique in each array, it may be easier to keep track of your ongoing sum by using an object rather than an array and using x values as keys, and then converting it into an array when you're done. E.g.:

function sumYValues(arrays) {
    var outer, inner, ar, entry, sum, result, x;

    sum = {};
    for (outer = 0; outer < arrays.length; ++outer) {
        ar = arrays[outer];
        for (inner = 0; inner < arrays.length; ++inner) {
            entry = ar[inner];
            sum[entry.x] = (sum[entry.x] || 0) + entry.y;
        }
    }

    result = [];
    for (x in sum) {
        result.push({x: x, y: sum[x]});
    }

    return result;
}

The above is mostly just to demonstrate using sum, an object, as a map of x => y values, although it does implement at least some of the summing logic as well.

This line may need some explanation:

            sum[entry.x] = (sum[entry.x] || 0) + entry.y;

If sum doesn't have an entry for that x value, sum[entry.x] will be undefined, which is a "falsey" value. So we use the curiously-powerful || operator to either get the value for that x from sum or 0, and then add the current entry's y to it and store the result.

这篇关于聚合JavaScript数组的对象值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆