简体   繁体   English

如果第一个值相同,则Javascript将第二个数组值相加

[英]Javascript add 2nd array values together if first values are the same

Sorry if the title isn't that clear. 抱歉,标题不清楚。 This is kind of hard to explain for me, as I'm not that good when it comes to multiple arrays. 这对我来说很难解释,因为涉及多个数组时,我的表现并不好。

I have an array: [ [21, 1000], [21, 500], [18, 100], [18, 200] ] 我有一个数组: [ [21, 1000], [21, 500], [18, 100], [18, 200] ]

Now I want to get this resulting array: [ [21, 1500], [18, 300] ] 现在我想得到这个结果数组: [ [21, 1500], [18, 300] ]

How do I go about doing this? 我该怎么做呢?

I've tried using 21 and 18 as array keys , but this way I couldn't use the array in a for loop with .length counting. 我曾尝试使用21和18作为数组 ,但是这种方式无法在带有.length计数的for循环中使用数组。 I ended up with a total of 4 arrays to almost get it working. 我最终得到了总共4个阵列,几乎可以正常工作。


Edit: 编辑:

I want to avoid using the 21 and 18 values as array keys. 我想避免使用21和18值作为数组键。

I also want to be able to iterate over the resulting array/object, and use the 21 and 18 "keys" as well, to make some further changes to my page. 我还希望能够遍历所得到的数组/对象,并同时使用21和18个“键”对我的页面进行一些进一步的更改。

Thanks already for all the responses! 已经感谢所有答复!

How about creating an object : 如何创建对象:

var arr = [ [21, 1000], [21, 500], [18, 100], [18, 200] ];
    obj = {};

for (i=0; i<arr.length; i++) {
    obj[arr[i][0]] = (obj[arr[i][0]] || 0) + arr[i][1];
}

// obj now equals {18: 300, 21: 1500} 
// obj[21] equals 1500 etc

FIDDLE 小提琴

You could create an array the same way : 您可以通过以下方式创建数组:

var arr  = [ [21, 1000], [21, 500], [18, 100], [18, 200] ],
    arr2 = [];

for (i=0; i<arr.length; i++) {
    arr2[arr[i][0]] = (arr2[arr[i][0]] || 0) + arr[i][1];
}

// giving you the array [18: 300, 21: 1500]
// where arr2[18] equals 300

You definitely don't need any jQuery for this to get the result array you asked for: 您绝对不需要任何jQuery来获取您要求的结果数组:

var one = [21, 18];
var two = [ [21, 1000], [21, 500], [18, 100], [18, 200] ];
var results = [];

for(var i in one) {
    results[i] = 0;

    for(var x in two)
        if(two[x][0] === one[i])
            results[i] = results[i] + two[x][1];

    results[i] = [one[i], results[i]];
}

Fiddle here 在这里摆弄

in case your values are not in order, you can use this: 如果您的值不正确,可以使用以下方法:

fiddle: 小提琴:
http://jsfiddle.net/acturbo/YWaja/ http://jsfiddle.net/acturbo/YWaja/

javasript: javasript:

var array1=    [21, 18];
var array2 =   [ [21, 1000], [21, 500], [18, 100], [18, 200] ];
var result =   [ [0,0], [0,0] ];

for (i=0;i<array1.length;i++){

    result[0,i][0] = array1[i];

    for (j=0;j<array2.length;j++){

        var key = array2[i,j][0];
        var val = array2[i,j][1];

        if (  key == array1[i] ){
            result[0,i][1] += val;
        }
    }
}

Here is another possibility, it is using Array.forEach , so you need to have a modern browser or use one of the many "shims"/"polyfills" out there. 这是另一种可能,它正在使用Array.forEach ,因此您需要使用现代的浏览器或使用许多“填充” /“填充”中的一种。

Javascript Java脚本

var first = [21, 18],
    second = [
        [21, 1000],
        [21, 500],
        [18, 100],
        [18, 200]
    ],
    store = {};
    result = [];


first.forEach(function (element) {
    second.forEach(function (pair) {
        var value;

        if (pair[0] === element) {
            value = store[element] || 0;
            store[element] = value + pair[1];
        }
    });

    if (typeof store[element] === "number") {
        result.push([element, store[element]]);
    }
});

console.log(result);

On jsfiddle jsfiddle上

Update: here is a solution based on the updated question, this also uses Object.keys and Array.map to do the conversion from an object to the array format that the OP has requested. 更新:这是基于更新的问题的解决方案,它也使用Object.keysArray.map进行从对象到OP所请求的数组格式的转换。

Javascript Java脚本

var first = [
        [21, 1000],
        [21, 500],
        [18, 100],
        [18, 200]
    ],
    store = {};
    result;

first.forEach(function (pair) {
    store[pair[0]] = (store[pair[0]] || 0) + pair[1];
});

result = Object.keys(store).map(function (key) {
    return [parseInt(key, 10), store[key]];
});

console.log(result);

On jsfiddle jsfiddle上

function aggregateResults(indexes, inputArray) {
  var ret = [], tmp;
  for (var i=0; i<indexes.length; i++) {
    tmp = 0;
    for (var j=0; j<inputArray.length; j++) {
      tmp += inputArray[j][0] == indexes[i] ? inputArray[j][1] : 0;
    }
    ret.push([indexes[i], tmp])
  }
  return ret;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM