VOOZH about

URL: https://www.geeksforgeeks.org/javascript/sum-of-distinct-elements-of-an-array-using-javascript/

⇱ Sum of Distinct Elements of an Array using JavaScript - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of Distinct Elements of an Array using JavaScript

Last Updated : 5 Aug, 2025

One can find a Sum of distinct elements (unique or different numbers) present in an array using JavaScript. Below is an example to understand the problem clearly.

Example:

Input: [ 1,2, 3, 1, 3, 4, 5, 5, 2] 
Output: 15
Explanation: The distinct elements present in array are: 1, 2, 3, 4 and 5
Sum = 1 + 2 + 3 + 4 + 5 = 15

There are several approaches to Calculate the Sum of distinct elements of an array using JavaScript:

Brute Force Approach

Sort the array so that duplicate elements comes together. Now Iterate through the sorted array and add each distinct element to the sum. Skip adding if the current element is the same as the previous one(i.e. Duplicate Elements). Return the final Sum.

Example: To demonstrate finding sum of distinct elements of an array using brute force approach.


Output
Sum of distinct elements: 15

Time complexity: O(n log n)

Space complexity: O(1)

Using a Set

Create a Set to store distinct elements. Now Iterate through the array and add each element to the Set. Iterate through the Set and calculate the sum of its elements. Return the final Sum.

Example: To demonstrate finding sum of distinct elements of an array using a Set.


Output
Sum of distinct elements: 15

Time complexity: O(n + m)

Space complexity: O(n)

Using an Object/Map

Create an empty object or Map to store unique elements as keys. Now, Iterate through the array, and for each element, add it as a key to the object or Map. Calculate the sum of all keys in the object or Map. Return the final Sum.

Example: To demonstrate finding sum of distinct elements of an array using an object map.


Output
Sum of distinct elements: 15

Time complexity: O(n + m)

Space complexity: O(n)

Using filter and indexOf Methods

In this approach, we'll filter out the distinct elements from the array by checking if the current element's index matches the first occurrence of that element in the array. Then, we'll calculate the sum of these distinct elements and return the result.

Example: To demonstrate finding the sum of distinct elements of an array using filter and indexOf methods.


Output
Sum of distinct elements: 29

Using Reduce and a Set for Efficient Summation

In this approach, we use the reduce method to efficiently calculate the sum of distinct elements in the array. We utilize a Set to keep track of the unique elements encountered during the reduction process. This method combines the power of reduce and Set for a concise and efficient solution.

Example:


Output
15
150
5


Comment