Summing up unique array values in JavaScript

We are required to write a JavaScript function that takes in an array of numbers that may contain some duplicate numbers. Our function should return the sum of all the unique elements (elements that only appear once in the array) present in the array.

Problem Understanding

If the input array is:

const arr = [2, 5, 5, 3, 2, 7, 4, 9, 9, 11];

The unique elements (appearing only once) are: 3, 7, 4, 11. Their sum is 3 + 7 + 4 + 11 = 25.

Using indexOf() and lastIndexOf()

We can identify unique elements by checking if their first and last occurrence positions are the same:

const arr = [2, 5, 5, 3, 2, 7, 4, 9, 9, 11];

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

25

Using Map for Better Performance

For larger arrays, counting occurrences with a Map is more efficient:

const arr = [2, 5, 5, 3, 2, 7, 4, 9, 9, 11];

const sumUniqueWithMap = arr => {
    const countMap = new Map();
    
    // Count occurrences
    for(let num of arr) {
        countMap.set(num, (countMap.get(num) || 0) + 1);
    }
    
    // Sum elements with count = 1
    let sum = 0;
    for(let [num, count] of countMap) {
        if(count === 1) {
            sum += num;
        }
    }
    
    return sum;
};

console.log(sumUniqueWithMap(arr));
25

Using reduce() Method

A functional approach using reduce() with filter():

const arr = [2, 5, 5, 3, 2, 7, 4, 9, 9, 11];

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

console.log(sumUniqueReduce(arr));
25

Performance Comparison

Method Time Complexity Space Complexity Best For
indexOf/lastIndexOf O(n²) O(1) Small arrays
Map counting O(n) O(n) Large arrays
reduce + filter O(n²) O(n) Functional style

Conclusion

Use the Map-based approach for better performance with large arrays, or the indexOf/lastIndexOf method for simplicity with smaller datasets. All methods correctly identify and sum unique elements that appear exactly once.

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

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements