Hasanuzzaman
Hasanuzzaman

Reputation: 618

How can I sum all unique numbers of an array?

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

Answers (4)

Krisztián Balla
Krisztián Balla

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

Adrian Brand
Adrian Brand

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

Nikhil Aggarwal
Nikhil Aggarwal

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

Mohammad Usman
Mohammad Usman

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

Related Questions