Sum of Distinct Elements of an Array using JavaScript
Last Updated :
25 Jun, 2024
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.
JavaScript
function sumElements(arr) {
arr.sort((a, b) => a - b);
let sum = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] !== arr[i - 1]) {
sum += arr[i];
}
}
return sum;
}
const array = [1, 2, 3, 2, 4, 3, 5, 6, 8, 2];
console.log("Sum of distinct elements:", sumElements(array));
OutputSum 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.
JavaScript
function sumElements(arr) {
const distinctSet = new Set(arr);
let sum = 0;
for (let num of distinctSet) {
sum += num;
}
return sum;
}
const array = [1, 2, 3, 2, 4, 3, 5];
console.log("Sum of distinct elements:", sumElements(array));
OutputSum 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.
JavaScript
function sumElements(arr) {
const distinctMap = {};
let sum = 0;
for (let num of arr) {
distinctMap[num] = true;
}
for (let key in distinctMap) {
sum += parseInt(key);
}
return sum;
}
const array = [1, 2, 3, 2, 4, 3, 5];
console.log("Sum of distinct elements:", sumElements(array));
OutputSum 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.
JavaScript
function sumElements(arr) {
const distinctElements = arr.filter((item, index) => arr.indexOf(item) === index);
let sum = 0;
for (let num of distinctElements) {
sum += num;
}
return sum;
}
const array = [1, 2, 3, 2, 4, 3, 5, 6, 8, 2];
console.log("Sum of distinct elements:", sumElements(array));
// Output
// Sum of distinct elements: 31
OutputSum 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:
JavaScript
function sumOfDistinctElements(arr) {
const result = arr.reduce((acc, curr) => {
if (!acc.set.has(curr)) {
acc.set.add(curr);
acc.sum += curr;
}
return acc;
}, { set: new Set(), sum: 0 });
return result.sum;
}
// Examples
const arr1 = [1, 2, 3, 1, 3, 4, 5, 5, 2];
console.log(sumOfDistinctElements(arr1)); // Output: 15
const arr2 = [10, 20, 20, 30, 10, 40, 50];
console.log(sumOfDistinctElements(arr2)); // Output: 150
const arr3 = [5, 5, 5, 5, 5];
console.log(sumOfDistinctElements(arr3)); // Output: 5
Similar Reads
Finding Sum of Alternate Elements of the Array using JavaScript Given an array, our task is to find the sum of alternative elements of the array using JavaScript. Example: Input: array = { 1, 2, 3, 4, 5, 6, 7, 8}Output: 16 Explanation:Sum of alternate elements of array = 1 + 3 + 5 + 7 = 16 Table of Content Using a for-loopUsing reduce Method Using Filter and Red
3 min read
Sum of Middle Elements of Two Sorted Arrays using JavaScript Given 2 sorted arrays Array1 and Array2 of size n each. Merge the given arrays and find the sum of the two middle elements of the merged array. Example: Input: array1 = [1, 3, 5] array2 = [2, 4, 6] n = 3 Output: 7 Explanation: Given two sorted arrays ar1 and ar2 of size n each: ar1 = [1, 3, 5] and a
5 min read
Sum of all subsets in array using JavaScript We are given an array, we have to print the sum of the subset generated. If the number of elements in the array is n, then 2n subset will be generated. One empty subset will also be generated. So the total subset generated is (2n + 1). Example: Input: 1 , 2, 3 Output: 0 , 1 , 2 , 3 , 3 , 4 , 5 , 6Ex
3 min read
JavaScript Program of Absolute Sum of Array Elements Using JavaScript, one can find the absolute sum of all elements present in an array. Below is an example to understand the problem clearly. Example:Input: [ -4, -7, 3, 10, 12] Output: 36 Explanation: Absolute values: 4 + 7 + 3 + 10 + 12 = 36 There are several approaches for finding the absolute sum
3 min read
JavaScript Program to Count Distinct Elements in Every Window In this problem we are given an array of integers and a number M. We have to find the count of distinct elements in every window of size M in the array using JavaScript. Example: Input: arr[] = [1, 2, 1, 3, 4, 2, 3], K = 4Output: 3 4 4 3Explanation: First window is [1, 2, 1, 3], count of distinct nu
4 min read