

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Filter unique array values and sum in JavaScript
Suppose, we have an array of arrays like this −
const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]];
We are supposed to write a function that takes in one such array. Notice that all the subarrays have precisely three elements in them.
Our function should filter out that subarray which has a repeating value as its first element. Moreover, for the subarray, we remove we should add their third element to its existing nonrepeating counterpart.
So, for the above array, the output should look like −
const output = [[12345, "product", "25"],[1234567, "other", "10"]];
Example
The code for this will be −
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)){ const newAmount = +amount + +res[map[id] - 1][2]; res[map[id] - 1][2] = '' + newAmount; }else{ map[id] = res.push(el); } }); return res; } console.log(addSimilar(arr));
Output
And the output in the console will be −
[ [ 12345, 'product', '25' ], [ 1234567, 'other', '10' ] ]
- Related Questions & Answers
- Finding the sum of unique array values - JavaScript
- JavaScript: How to filter out Non-Unique Values from an Array?
- Filter array with filter() and includes() in JavaScript
- Summing up unique array values in JavaScript
- Extract unique values from an array - JavaScript
- Find unique and biggest string values from an array in JavaScript
- Filter away object in array with null values JavaScript
- Summing all the unique values of an array - JavaScript
- How to get all unique values in a JavaScript array?
- Sum all duplicate values in array in JavaScript
- JavaScript reduce sum array with undefined values
- Making array unique in JavaScript
- Sum of nested object values in Array using JavaScript
- Sum from array values with similar key in JavaScript
- Filter one array with another array - JavaScript
Advertisements