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
Selected Reading
Sum all duplicate values in array in JavaScript
We need to write a JavaScript function that takes an array of numbers with duplicate entries and sums all duplicate values. Each unique number appears once in the result, multiplied by its frequency count.
Problem Understanding
For array [1, 3, 1, 3, 5, 7, 5, 3, 4]:
- 1 appears 2 times ? 1 × 2 = 2
- 3 appears 3 times ? 3 × 3 = 9
- 5 appears 2 times ? 5 × 2 = 10
- 7 appears 1 time ? 7 × 1 = 7
- 4 appears 1 time ? 4 × 1 = 4
Using Map to Count and Sum
This approach uses a Map to count occurrences, then multiplies each unique value by its count:
const input = [1, 3, 1, 3, 5, 7, 5, 3, 4];
const sumDuplicate = 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(sumDuplicate(input));
[ 2, 9, 10, 7, 4 ]
Using Object for Counting
Alternative approach using a plain object instead of Map:
const input = [1, 3, 1, 3, 5, 7, 5, 3, 4];
const sumDuplicateWithObject = arr => {
const count = {};
// Count occurrences
arr.forEach(num => {
count[num] = (count[num] || 0) + 1;
});
// Multiply each number by its count
return Object.keys(count).map(key => parseInt(key) * count[key]);
};
console.log(sumDuplicateWithObject(input));
[ 2, 9, 10, 7, 4 ]
Using forEach for Direct Calculation
More readable approach that separates counting and multiplication:
const input = [1, 3, 1, 3, 5, 7, 5, 3, 4];
const sumDuplicateSimple = arr => {
const frequency = new Map();
// Count frequencies
arr.forEach(num => {
frequency.set(num, (frequency.get(num) || 0) + 1);
});
// Calculate sums
const result = [];
frequency.forEach((count, value) => {
result.push(value * count);
});
return result;
};
console.log(sumDuplicateSimple(input));
[ 2, 9, 10, 7, 4 ]
Comparison
| Method | Pros | Cons |
|---|---|---|
| Map with reduce | Functional style, concise | Complex one-liner |
| Object counting | Familiar syntax | Requires parseInt conversion |
| forEach approach | Most readable | More verbose |
Conclusion
All methods count duplicate occurrences and multiply each unique value by its frequency. Choose based on readability preference and team coding standards.
Advertisements
