Sum of distinct elements of an array in JavaScript

Suppose, we have an array of numbers like this −

const arr = [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1];

We are required to write a JavaScript function that takes in one such array and counts the sum of all distinct elements of the array.

For example:

The output for the array mentioned above will be −

30

Method 1: Using lastIndexOf() and indexOf()

This approach checks if the current index is the last occurrence of each element, ensuring we count each distinct element only once.

const arr = [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1];

const distinctSum = arr => {
    let res = 0;
    for(let i = 0; i 

30

Method 2: Using Set for Unique Elements

A more modern approach uses Set to automatically filter unique values, then calculates their sum.

const arr = [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1];

const distinctSumWithSet = arr => {
    const uniqueElements = [...new Set(arr)];
    return uniqueElements.reduce((sum, num) => sum + num, 0);
};

console.log(distinctSumWithSet(arr));
30

Method 3: Using Map to Track Occurrences

This approach uses a Map to count occurrences and sum only unique elements.

const arr = [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1];

const distinctSumWithMap = arr => {
    const elementMap = new Map();
    
    // Count occurrences
    for(let num of arr) {
        elementMap.set(num, (elementMap.get(num) || 0) + 1);
    }
    
    // Sum unique elements
    let sum = 0;
    for(let [key] of elementMap) {
        sum += key;
    }
    
    return sum;
};

console.log(distinctSumWithMap(arr));
30

Comparison

Method Time Complexity Space Complexity Readability
lastIndexOf() O(n²) O(1) Good
Set + reduce() O(n) O(n) Excellent
Map tracking O(n) O(n) Good

Conclusion

The Set-based approach offers the best combination of performance and readability. For large arrays, avoid the lastIndexOf() method due to its O(n²) complexity.

Updated on: 2026-03-15T23:19:00+05:30

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements