How to use filter and indexOf Methods In Javascript
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.
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
Output
Sum of distinct elements: 29
Sum of Distinct Elements of an Array using JavaScript
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:
Table of Content
- Brute Force Approach
- Using a Set
- Using an Object/Map
- Using filter and indexOf Methods