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.
(1) Use Array#reduce() and Object.assign() to build an object with unique keys (and values summed):
{ car: 8000, ball: 400, piano: 2500 }
(2) Use Object.keys() to get new array1:
[ 'car', 'ball', 'piano' ]
(3) Use Object.values() to get new array2:
[ 8000, 400, 2500 ]
DEMO 1
let array1 = ['car', 'car', 'ball', 'piano', 'car'];
let array2 = ['2500', '1000', '400', '2500', '4500'];
const result = array1.reduce((acc, cur, index) => Object.assign(acc, {
[cur]: (acc[cur] || 0) + +array2[index]
}), {});
array1 = Object.keys(result);
array2 = Object.values(result);
console.log(array1);
console.log(array2);
You can also return an object literal directly in Array#reduce() as follows:
const result = array1.reduce((acc, cur, index) => ({
...acc,
[cur]: ((acc[cur] || 0) + +array2[index])
}), {});
DEMO 2
let array1 = ['car', 'car', 'ball', 'piano', 'car'];
let array2 = ['2500', '1000', '400', '2500', '4500'];
const result = array1.reduce((acc,cur,index) => ({...acc,[cur]:((acc[cur] || 0) + +array2[index])}), {});
array1 = Object.keys(result);
array2 = Object.values(result);
console.log(array1);
console.log(array2);
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)
Not exactly the best solution, but should work. I have used the map to create an index and add the values. It is a simple one.
let array1 = ['car', 'car', 'ball', 'piano', 'car', 'ball', 'piano'];
let array2 = ['2500', '1000', '400', '2500', '4500', '2500', '4500'];
const MapOfItems = new Map();
array1.forEach(function(item, index) {
if (MapOfItems.has(item))
MapOfItems.set(item, MapOfItems.get(item) + +array2[index]);
else
MapOfItems.set(item, +array2[index]);
});
console.log(MapOfItems);
console.log(MapOfItems.keys());
console.log(MapOfItems.values());