如果我有一个数组,比如:
var array = [[1,"GOOG",4],[1,"GOOG",6],[2,"GOOG",4],[2,"FB",4]];
使用javascript,我如何将其转换为数组,其中包含arrayi中相同的第二个值的所有项(在示例中,前3个具有相同的GOOG值,并将它们的第三个值arrayi相加并组合在一起,从而得到以下数组。
var array = [["GOOG",14],["FB",4]];
编辑:实际上,我需要所有的项目匹配,阿拉伊添加和合并。
发布于 2017-02-03 17:47:05
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);
https://stackoverflow.com/questions/42035590
复制相似问题