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
Selected Reading
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.
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];
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
[ 40, 20, 30 ]
Advertisements
