如果我有一个像:
这样的数组var array = [[1,"GOOG",4],[1,"GOOG",6],[2,"GOOG",4],[2,"FB",4]];
使用javascript,我怎么能把它变成一个数组,其中所有项目在array [i] [1]中包含相同的第二个值(在示例中前3个具有相同的GOOG值并得到它们的第三个值数组[i] [2]加在一起并合并得到以下数组。
var array = [["GOOG",14],["FB",4]];
编辑:实际上我需要添加和组合数组[i] [1]的所有项目。
答案 0 :(得分:1)
var array = [[1,"GOOG",4],[1,"GOOG",6],[2,"GOOG",4],[2,"FB",4]];
var result = array.reduce(function(acc, item) {
// check if an item with the same second (item[1]) value already exist
var index = -1;
acc.forEach(function(e, i) {
if(e[0] == item[1])
index = i;
});
// if it does exist
if (index != -1)
acc[index][1] += item[2]; // add the value of the current item third value (item[2]) to it's second value (acc[index][1])
// if it does not
else
acc.push([item[1], item[2]]); // push a new element
return acc; // return the accumulator (see reduce docs)
}, []);
console.log(result);