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
Adding up identical elements in JavaScript
We are required to write a JavaScript function that takes in an array of numbers and sums all the identical numbers together at one index.
Problem Overview
When we have an array with duplicate values, we want to combine them into a single occurrence with their sum. The first occurrence of each unique number will contain the total sum of all occurrences.
Example Input and Output
If the input array is:
const arr = [20, 10, 15, 20, 15, 10];
Then the output should be:
const output = [40, 20, 30];
Here, 20 appears twice (20 + 20 = 40), 10 appears twice (10 + 10 = 20), and 15 appears twice (15 + 15 = 30).
Method 1: Using splice() and lastIndexOf()
This approach modifies the original array by finding duplicates and adding their values to the first occurrence:
const arr = [20, 10, 15, 20, 15, 10];
const addSimilar = arr => {
for(let i = 0; i
[ 40, 20, 30 ]
Method 2: Using Map for Frequency Count
This approach creates a new array without modifying the original:
const arr = [20, 10, 15, 20, 15, 10];
const addSimilarWithMap = arr => {
const seen = new Map();
const result = [];
for(let num of arr) {
if(!seen.has(num)) {
const sum = arr.filter(x => x === num).reduce((a, b) => a + b, 0);
result.push(sum);
seen.set(num, true);
}
}
return result;
};
console.log(addSimilarWithMap(arr));
console.log("Original array:", arr); // Unchanged
[ 40, 20, 30 ]
Original array: [ 20, 10, 15, 20, 15, 10 ]
How It Works
Method 1 uses lastIndexOf() to find the last occurrence of each duplicate and combines it with the first occurrence using splice(). Method 2 maintains order by tracking seen values and calculating sums without modifying the original array.
Comparison
| Method | Modifies Original | Time Complexity | Space Complexity |
|---|---|---|---|
| splice() + lastIndexOf() | Yes | O(n²) | O(1) |
| Map + filter() | No | O(n²) | O(n) |
Conclusion
Both methods effectively sum identical elements while preserving order. Choose the first method if you want to modify the original array, or the second method if you prefer keeping the original intact.
