简体   繁体   中英

Javascript Array duplicates and values

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?

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; } 

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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