简体   繁体   English

Javascript数组重复项和值

[英]Javascript Array duplicates and values

This is my first Stack Overlow question: 这是我的第一个Stack Overlow问题:

I got this array [['a',12],['a',21],['b',1],['c',4],['c',5]] 我得到了这个数组[['a',12],['a',21],['b',1],['c',4],['c',5]]

and I want to output it like this [['a',33],['b',1],['c',9]] 我想像这样[['a',33],['b',1],['c',9]]

Anyone can give me an helping hand? 有人可以帮我吗?

You could use a hash table for referencing the same result array with the same first item of the inner array. 您可以使用哈希表来引用与内部数组的第一项相同的结果数组。

The Array#forEach loops the array and looks if the string is already in the hash table. Array#forEach循环数组并查看字符串是否已在哈希表中。 If not, then assign a copy of the inner array and push it to the result as well, then exit the callback. 如果不是,则分配内部数组的副本,并将其也推到结果中,然后退出回调。

If found, add the value of the inner array to the array of the hash table. 如果找到,则将内部数组的值添加到哈希表的数组中。

 var data = [['a', 12], ['a', 21], ['b', 1], ['c', 4], ['c', 5]], hash = Object.create(null), // generate object without prototypes result = []; data.forEach(function (a) { if (!(a[0] in hash)) { hash[a[0]] = a.slice(); result.push(hash[a[0]]); return; } hash[a[0]][1] += a[1]; }); console.log(result); console.log(hash); // to show how it works 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Use Array.reduce : 使用Array.reduce

var data = [['a', 12], ['a', 21], ['b', 1], ['c', 4], ['c', 5]];

var result = data.reduce(function (a, b, i) {
    const c = a.filter(function (ax) { return ax[0] === b[0] });
    c.length > 0 ? c[0][1] = c[0][1] + b[1] : a.push(b);
    return a;
}, []);

console.log(result);
// [[a, 33], [b, 1], [c, 9]]

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

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