如何找到具有相同值的所有数组?

时间:2014-04-16 11:14:43

标签: javascript arrays

我有一个数组,里面有几个数组,就像那样:

var arrs = [
  ['qqq', 5],
  ['www', 2],
  ['qqq', 15],
  ['qqq', 11],
  ['www', 1],
  ['eee', 22]
];

如何找到具有相同值的所有数组并将它们合并为一个数组,如:

[
    ['qqq', 31],
    ['www', 3]
];

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

您应该使用新的“results”数组来存储输出。然后循环输入数组并添加到结果中(如果是新结果),或者如果找到匹配则更新结果。

这样的事情:

var arrs = [
    ['qqq', 5],
    ['www', 2],
    ['qqq', 15],
    ['qqq', 11],
    ['www', 1],
    ['eee', 22]
];

function sumDuplicates(arr) {
    var results = [];//array to hold the results
    //loop the input array so we can process each item
    for (var i = 0; i < arr.length; i++) {
        var current = arr[i];//get the current item we are processing
        var match = null;//this will hold a match, IF we find one
        //loop the results to look for an existing match
        for (var j = 0; j < results.length; j++) {
            var item = results[j];//get the item in the results that we want to check for match
            //check if we have found a match
            if (item[0] === current[0]) {
                match = item;//match found so store the match for later
                break;//match found so break the loop
            }
        }
        //no match found, so add the current item to the results (so it can be matched later)
        if (!match) results.push(current);
        //match found, so increment the stored value
        else match[1] = match[1] + current[1];
    }

    return results;
}

var result = sumDuplicates(arrs);
console.log(result);

Here is a working example

请注意,这也包括非重复项(例如'eee'),这对我来说很有意义。如果你出于某种原因需要删除没有重复的项目,请告诉我