How to Get The Sum Of All Numbers In A Set Using JavaScript

This article will share some solutions to get the sum of all numbers in a Set using JavaScript. Let’s get started.

How to get the sum of all numbers in a Set

The Set objects are collections of values. A value in the Set may only occur once. You can iterate through the elements of the Set object in insertion order.

To get the sum of all numbers in a Set, we need to create a let variable representing the sum of the numbers in the Set. Declaring the let variable allows us to update the value of the variable.

Because the Set object has the properties of an array, we can use the forEach() method to call a function on each element of the Set.

The complete code to get the sum of all numbers in a Set using the forEach() method is as follows:

// Create a Set object
const setObj = new Set([5, 4, 3, 2, 1]);
console.log(setObj);

let sum = 0;

// Get the sum of all numbers in a Set using the forEach() method
setObj.forEach((number) => {
sum += number;
});

console.log("The sum of all numbers in the 'setObj' Set");
console.log(sum);

Output:

Set(5) { 5, 4, 3, 2, 1 }
The sum of all numbers in the 'setObj' Set
15

Another solution to get the sum of all numbers in a Set is to use the reduce() method.

The reduce() method is used to reduce the values of an array to a single value. This method executes a function for each array element (from left to right) and does not mutate the original array.

Syntax:

array.reduce(function(), initialValue)

Parameters:

function(): a function to be executed for each element.

initialValue: the initial value.

However, the reduce() method only works on array objects. If you want to use this method on a Set object, you must convert this Set object to an array object using the Array.from() method.

Example:

// Create a Set object
const setObj = new Set([5, 4, 3, 2, 1]);
console.log(setObj);

// Convert the 'setObj' Set object to an array object
const setArray = Array.from(setObj);

// Get the sum of all numbers in a Set using the reduce() method
function getSum(sum, number) {
return sum + number;
}

const sum = setArray.reduce(getSum, 0);
console.log("The sum of all numbers in the 'setObj' Set");
console.log(sum);

Output:

Set(5) { 5, 4, 3, 2, 1 }
The sum of all numbers in the 'setObj' Set
15

Summary

This article shared two solutions to get the sum of all numbers in a Set using JavaScript. If you use reduce() method, remember to convert the Set object to an array object. If you use the forEach() method, declare the variable that stores the sum as a let variable so that we can update the variable’s value. Thank you for reading.