1

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.

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
Hasanuzzaman
  • 558
  • 1
  • 4
  • 11

4 Answers4

4

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);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
2

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);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
  • 1
    function houseNumbersSum(inputArray) { return inputArray.slice(0, inputArray.indexOf(0)).reduce((s, v) => s+v, 0); };houseNumbersSum(inputArray) //It works good also. – Hasanuzzaman Sep 15 '18 at 14:04
  • @Hasanuzzaman - There are many ways to achieve it. However, the above will not remove duplicates. – Nikhil Aggarwal Sep 15 '18 at 14:07
0

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);
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
0

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.

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84