Sum of distinct elements of an array - JavaScript

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: Suppose, we have an array of numbers like this ?

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

The distinct elements are: 1, 5, 2, 3, 4, 7, 8. Their sum is: 1 + 5 + 2 + 3 + 4 + 7 + 8 = 30.

Using lastIndexOf() Method

This approach checks if the current index matches the last occurrence of the element, ensuring we only add each distinct element 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 < arr.length; i++){
        if(i === arr.lastIndexOf(arr[i])){
            res += arr[i];
        }
    }
    return res;
};

console.log(distinctSum(arr));
30

Using Set for Distinct Elements

A cleaner approach uses Set to automatically handle uniqueness:

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));
console.log("Distinct elements:", [...new Set(arr)]);
30
Distinct elements: [ 1, 5, 2, 3, 4, 7, 8 ]

Using Filter with indexOf

This method filters elements that appear at their first occurrence position:

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

const distinctSumWithFilter = arr => {
    return arr
        .filter((value, index) => arr.indexOf(value) === index)
        .reduce((sum, num) => sum + num, 0);
};

console.log(distinctSumWithFilter(arr));
30

Comparison

Method Time Complexity Readability Memory Usage
lastIndexOf() O(n²) Good O(1)
Set O(n) Excellent O(n)
Filter + indexOf O(n²) Good O(n)

Conclusion

The Set approach is most efficient and readable for finding the sum of distinct elements. Use lastIndexOf() for memory-constrained environments where you need O(1) extra space.

Updated on: 2026-03-15T23:18:59+05:30

565 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements