Get the Sum of all Numbers in a Set using JavaScript

Borislav Hadzhiev

Sat Oct 30 2021ยท2 min read

Photo by Dingzeyu Li

**To get the sum of the numbers in a Set:**

- Initialize a
`sum`

variable and set it to`0`

. - Use the
`forEach()`

method to iterate over the`Set`

. - On each iteration, add the number to the
`sum`

, reassigning the variable.

index.js

Copied!`const set1 = new Set([1, 2, 3, 4]); let sum = 0; set1.forEach(num => { sum += num; }); console.log(sum); // ๐๏ธ 10`

The function we passed to the
Set.forEach
method gets called with each element in the `Set`

object.

**On each iteration, we add the number to the value of sum and reassign the
variable to the result.**

Note that the

`sum`

variable is declared using the `let`

keyword. Had the variable been declared using `const`

, we wouldn't be able to reassign it.This gives us the total of all the numbers in the `Set`

.

An alternative, and more functional approach is to convert the `Set`

to an array
and use the
Array.reduce
method.

**To get the sum of the numbers in a Set:**

- Convert the
`Set`

to an array. - Use the
`reduce()`

method to iterate over the array. - On each iteration, add the number to the accumulator and return the result.

index.js

Copied!`const set1 = new Set([1, 2, 3, 4]); const arr = Array.from(set1); console.log(arr); // ๐๏ธ [1, 2, 3, 4] const sum = arr.reduce((accumulator, current) => { return accumulator + current; }, 0); console.log(sum); // ๐๏ธ 10`

We used the
Array.from
method to convert the `Set`

into an array, so we can call the `reduce()`

method.

The second parameter we passed to the callback function in the

`reduce`

method is the initial value for the `accumulator`

variable, in our case `0`

.**On each iteration, we add the number to the accumulated value and return the
result.**

The accumulated value gets passed to the function on each iteration, until the sum of the elements is calculated.

This approach is very similar to the previous one, however using the `forEach`

method on the `Set`

might be more intuitive if you're not familiar with the
`reduce`

method.

I'll send you 1 email a week with links to all of the articles I've written that week