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.

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

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

Similar Reads

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....

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....

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....

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....