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
Filter unique array values and sum in JavaScript
In JavaScript, you may need to filter arrays that contain duplicate values and combine their numeric values. This is common when processing data like product orders, transactions, or inventory records.
Problem Statement
Given an array of arrays where each subarray has three elements [id, name, amount], we need to:
- Remove duplicate entries based on the first element (id)
- Sum the third element (amount) for matching entries
const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]];
The expected output should combine the duplicate entries and sum their amounts:
[[12345, "product", "25"], [1234567, "other", "10"]]
Solution Using Map for Tracking
const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]];
const addSimilar = (arr = []) => {
const res = [];
const map = {};
arr.forEach(el => {
const [id, name, amount] = el;
if(map.hasOwnProperty(id)){
// If ID exists, add amounts and update existing entry
const newAmount = +amount + +res[map[id] - 1][2];
res[map[id] - 1][2] = '' + newAmount;
} else {
// If new ID, add to result and track position
map[id] = res.push(el);
}
});
return res;
};
console.log(addSimilar(arr));
[ [ 12345, 'product', '25' ], [ 1234567, 'other', '10' ] ]
How It Works
The algorithm uses a map object to track which IDs have been processed:
- First occurrence: Store the entry in result array and record its position in the map
- Duplicate found: Add the amount to the existing entry's amount
-
Type conversion: Use
+amountto convert strings to numbers for addition - Result format: Convert sum back to string to maintain original data type
Alternative Approach Using reduce()
const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]];
const addSimilarReduce = (arr = []) => {
const grouped = arr.reduce((acc, [id, name, amount]) => {
if (acc[id]) {
acc[id][2] = '' + (+acc[id][2] + +amount);
} else {
acc[id] = [id, name, amount];
}
return acc;
}, {});
return Object.values(grouped);
};
console.log(addSimilarReduce(arr));
[ [ 12345, 'product', '25' ], [ 1234567, 'other', '10' ] ]
Comparison
| Method | Complexity | Readability | Memory Usage |
|---|---|---|---|
| Map tracking | O(n) | Good | Higher (separate result array) |
| Reduce approach | O(n) | Better | Lower (single object) |
Conclusion
Both approaches effectively filter duplicates and sum values. The reduce method is more concise, while the map tracking approach offers more explicit control over the result structure.
Advertisements
