How to sum same reference of arrays

Hi All,

I’ve 1 question, how should I sum the same array reference in javascript?

var a = ["R1", "R2", "R1", "R3"]; var b = [3,10,15,20]
The output of array will be like this:

Output: [18,10,20];

Thanks in advance!

I’d create an object where the elements of array 1 are the keys and the elements of array 2 are the values.

const obj = {
  "R1": 18,
  "R2": 10,
  "R3": 20,
}

You’d do that like this:

const a = ["R1", "R2", "R1", "R3"];
const b = [3,10,15,20];
const obj = {};

a.forEach(function(el, i){
  if (el in obj){
    obj[el] = obj[el] + b[i];
  } else {
    obj[el] = b[i];
  }
});

console.log(obj);

From there, it’s quite simple to convert back to an array:

const final = Object.keys(obj).map( (key, index) => obj[key]);

Here’s a demo.

Great! This is what I want, Thank you very much!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.