I need some help to sum values inside an array in order
I have two arrays:
array1 = ['car', 'car', 'ball', 'piano', 'car'] array2 = ['2500', '1000', '400', '2500', '4500']
I’m using this code below to remove the duplicated values inside array1:
var uniqueValues = []; for(var i in array1){ if(uniqueValues.indexOf(array1[i]) === -1){ uniqueValues.push(array1[i]); } } //returns ['car', 'ball', 'piano']
What I need is to sum the values of array2 using the order of array1, so I will have this result:
result = ['8000', '400', '2500']
So the final result would be this:
array1 = ['car', 'ball', 'piano'] array2 = ['8000', '400', '2500']
Any suggestion ? thank you.
Advertisement
Answer
Reduce will do the trick
NOTE Does JavaScript guarantee object property order?
let array1 = ['car', 'car', 'ball', 'piano', 'car'] let array2 = ['2500', '1000', '400', '2500', '4500'] const merged = array1.reduce((acc,cur,i) => { acc[cur] = (acc[cur] || 0) + +array2[i]; // add after casting to number return acc },{}) console.log(merged) array1 = Object.keys(merged) array2 = Object.values(merged) console.log(array1) console.log(array2)