H. Dervic - 1 year ago 73
Javascript Question

# Sum all same elements in one array

how can I sum all same elements in one array? For example I have an array:

``````  [20,20,20,10,10,5,1]
``````

How can I make it
`[60,20,5,1]`
?

Here's what I have tried so far:

``````var money = [20, 20, 20, 10, 10, 5, 1];
for (var i = 0; i < money.length; i++) {
if (money[i] == money[i + 1]) {
money[i] += money[i + 1];
money.splice(money.indexOf(money[i + 1]), 1);
}
}
``````

Use `Array#reduce` method with a variable to store previous element.

``````var arr = [20, 20, 20, 10, 10, 5, 1];
// variable for storing previous element
var prev;

var res = arr.reduce(function(arr, v) {
// if element is same as previous then add
// value with last element
if (prev == v)
arr[arr.length - 1] += v;
// else push and update prev variable
else
arr.push(prev = v)
// return the array refernece
return arr;
// set initial value as empty array for result
}, [])

console.log(res);``````

UPDATE : If same values are not adjacent then use an object to refer the index.

``````var arr = [20, 20, 20, 10, 10, 5, 1];
// object for refering index
var ref = {};

var res = arr.reduce(function(arr, v) {
// check property is defined or not if
// defined update value at the index
if (ref.hasOwnProperty(v))
arr[ref[v]] += v;
else {
// else add property to object and push element
ref[v] = arr.length;
arr.push(prev = v)
}
// return array reference
return arr;
// set initial value as empty array for result
}, [])

console.log(res);``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download