![]() |
VOOZH | about |
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.
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:
Table of Content
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.
Sum of distinct elements: 15
Time complexity: O(n log n)
Space complexity: O(1)
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.
Sum of distinct elements: 15
Time complexity: O(n + m)
Space complexity: O(n)
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.
Sum of distinct elements: 15
Time complexity: O(n + m)
Space complexity: O(n)
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.
Sum of distinct elements: 29
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:
15 150 5