 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Sum all similar elements in one array - 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
For example −
If the input array is −
const arr = [20, 10, 15, 20, 15, 10];
Then the output should be −
const output = [40, 20, 30];
Example
Following is the code −
const arr = [20, 10, 15, 20, 15, 10]; const addSimilar = arr => {    for(let i = 0; i < arr.length; i++){       while(i !== arr.lastIndexOf(arr[i])){          const ind = arr.lastIndexOf(arr[i]);          arr[i] += arr.splice(ind, 1)[0];       };    }; }; addSimilar(arr); console.log(arr);  Output
This will produce the following output in console −
[ 40, 20, 30 ]
Advertisements
 