Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Summing all the unique values of an array - JavaScript
Let's say, we are required to write a JavaScript function that takes in an array of numbers with duplicate entries and sums all the duplicate entries to one index.
For example ?
If the input array is ?
const input = [1, 3, 1, 3, 5, 7, 5, 4];
Then the output should be ?
const output = [2, 6, 10, 7, 4];
That means all the duplicate ones are summed to index 0 (1 + 1 = 2), all the duplicate threes are summed to index 1 (3 + 3 = 6), and so on. Each unique value is multiplied by its frequency count.
Using Map and reduce()
This approach uses Map to count occurrences and then multiplies each unique value by its count:
const input = [1, 3, 1, 3, 5, 7, 5, 4];
const mergeDuplicates = arr => {
const map = arr.reduce((acc, val) => {
if(acc.has(val)){
acc.set(val, acc.get(val) + 1);
}else{
acc.set(val, 1);
};
return acc;
}, new Map());
return Array.from(map, el => el[0] * el[1]);
};
console.log(mergeDuplicates(input));
[ 2, 6, 10, 7, 4 ]
Using Object for Counting
An alternative approach using a plain object instead of Map:
const input = [1, 3, 1, 3, 5, 7, 5, 4];
const mergeDuplicatesWithObject = arr => {
const counts = {};
// Count occurrences
arr.forEach(num => {
counts[num] = (counts[num] || 0) + 1;
});
// Multiply each unique value by its count
return Object.keys(counts).map(key => parseInt(key) * counts[key]);
};
console.log(mergeDuplicatesWithObject(input));
[ 2, 6, 10, 7, 4 ]
How It Works
The algorithm works in two phases:
- Count Phase: Count how many times each unique value appears
- Sum Phase: Multiply each unique value by its occurrence count
For the array [1, 3, 1, 3, 5, 7, 5, 4]:
- 1 appears 2 times ? 1 × 2 = 2
- 3 appears 2 times ? 3 × 2 = 6
- 5 appears 2 times ? 5 × 2 = 10
- 7 appears 1 time ? 7 × 1 = 7
- 4 appears 1 time ? 4 × 1 = 4
Comparison
| Method | Performance | Readability | Memory |
|---|---|---|---|
| Map with reduce() | Good | Moderate | Efficient |
| Object with forEach() | Good | Better | Efficient |
Conclusion
Both approaches effectively sum unique values by counting occurrences and multiplying by the value. The object-based method is more readable, while Map offers better type safety for keys.
