Reputation: 13
This is my first Stack Overlow question:
I got this array [['a',12],['a',21],['b',1],['c',4],['c',5]]
and I want to output it like this [['a',33],['b',1],['c',9]]
Anyone can give me an helping hand?
Upvotes: 0
Views: 75
Reputation: 4787
Use 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]]
Upvotes: 0
Reputation: 386530
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. 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; }
Upvotes: 1