Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add values in a two-dimensional array with JavaScript

Tags:

javascript

I want to merge and add the following 2D array:

var arr = [
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TEN", 10],
    ["FIVE", 5],
    ["ONE", 1],
    ["QUARTER", 0.25],
    ["QUARTER", 0.25],
    ["DIME", 0.1],
    ["DIME", 0.1],
    ["PENNY", 0.01],
    ["PENNY", 0.01],
    ["PENNY", 0.01],
    ["PENNY", 0.01]
    ];

Resulting in a 2D array that looks like this:

 arr = [
     ["TWENTY", 80],
     ["TEN", 10],
     ["FIVE", 5],
     ["QUARTER", 0.50],
     ["DIME", 0.20],
     ["PENNY", 0.04]
     ];

Basically I'm adding up the number values and condensing the string values. I tried map, reduce, and for loops but this one has me stumped.

like image 447
y2knoproblem Avatar asked Jul 09 '26 19:07

y2knoproblem


1 Answers

All you really need is a reduce and a map, which could probably add up to a good MapReduce joke.

var arr = [
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TWENTY", 20],
    ["TEN", 10],
    ["FIVE", 5],
    ["ONE", 1],
    ["QUARTER", 0.25],
    ["QUARTER", 0.25],
    ["DIME", 0.1],
    ["DIME", 0.1],
    ["PENNY", 0.01],
    ["PENNY", 0.01],
    ["PENNY", 0.01],
    ["PENNY", 0.01]
];
var obj = arr.reduce(function (out, el) {
    out[el[0]] = (out[el[0]] || 0) + el[1];
    return out;
}, {});
var out = Object.keys(obj).map(function (key) {
    return [key, obj[key]]
}); //[["TWENTY",80],["TEN",10],["FIVE",5],["ONE",1],["QUARTER",0.5],["DIME",0.2],["PENNY",0.04]]
like image 133
Etheryte Avatar answered Jul 12 '26 07:07

Etheryte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!