Reputation: 618
I've the following data:
var array = [2, 4, 12, 4, 3, 2, 2, 5, 0];
I want to sum 2 + 4 + 12 + 3 + 5
and want to show the result using JavaScript without any library, by simply using a for
loop and if
/else
statements.
Upvotes: 1
Views: 222
Reputation: 20371
Here is a simple solution using a loop:
const array = [2, 4, 12, 4, 3, 2, 2, 5, 0];
function sumNotCommon(array) {
const sortedArray = array.slice().sort();
let sum = 0;
for (let i = 0; i < sortedArray.length; ++i) {
if (i === 0 || sortedArray[i] !== sortedArray[i-1])
sum += sortedArray[i];
}
return sum;
}
console.log(sumNotCommon(array));
First it sorts the array and then iterates through it ignoring equal numbers that follow each other.
Upvotes: 0
Reputation: 21638
const distinct = (array) =>
array ? array.reduce((arr, item) => (arr.find(i => i === item) ? [...arr] : [...arr, item]), []) : array;
const sum = distinct([2,4,12,4,3,2,2,5,0]).reduce((a,b) => a + b);
console.log(sum);
Upvotes: 0
Reputation: 28465
you can try following using Set and Array.reduce
var array = [2,4,12,4,3,2,2,5,0];
let set = new Set();
let sum = array.reduce((a,c) => {
if(!set.has(c)) {set.add(c); a += c; }
return a;
}, 0);
console.log(sum);
Upvotes: 2
Reputation: 39332
You can make use of ES6 Sets
and .reduce()
method of arrays:
let array = [2, 4, 12, 4, 3, 2, 2, 5, 0];
let sum = [...new Set(array)].reduce((a, c) => (a + c), 0);
console.log(sum);
Upvotes: 4