Finding the sum of unique array values - 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.

For example, if the input array is:

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

Then the output should be 25 (3 + 7 + 4 + 11 = 25), as these are the only elements that appear exactly once.

Using indexOf() and lastIndexOf()

We can identify unique elements by comparing their first occurrence with their last occurrence. If they're the same, the element appears only once.

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 to Count Occurrences

A more efficient approach uses a Map to count element frequencies, then sums elements with count 1:

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 that appear only once
    let sum = 0;
    for(let [num, count] of countMap) {
        if(count === 1) {
            sum += num;
        }
    }
    
    return sum;
};

console.log(sumUniqueWithMap(arr));
25

Using filter() and Functional Approach

A more concise solution using array methods:

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

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

console.log(sumUniqueFunctional(arr));
25

Comparison

Method Time Complexity Readability
indexOf/lastIndexOf O(n²) Good
Map counting O(n) Good
Functional approach O(n²) Excellent

Conclusion

The Map-based approach offers the best performance for large arrays, while the functional approach provides the most readable code. Choose based on your specific needs for performance versus code clarity.

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements