
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Sum Elements at the Same Index in Array of Arrays in JavaScript
We have an array of arrays and are required to write a function that takes in this array and returns a new array that represents the sum of corresponding elements of original array.
If the original array is −
[ [43, 2, 21],[1, 2, 4, 54],[5, 84, 2],[11, 5, 3, 1] ]
Then the output should be −
[60, 93, 30, 55]
Let’s write a sample function addArray()
The full code for this function will be −
Example
const arr = [ [43, 2, 21],[1, 2, 4, 54],[5, 84, 2],[11, 5, 3, 1] ]; const sumArray = (array) => { const newArray = []; array.forEach(sub => { sub.forEach((num, index) => { if(newArray[index]){ newArray[index] += num; }else{ newArray[index] = num; } }); }); return newArray; } console.log(sumArray(arr));
Output
The output in the console will be −
[ 60, 93, 30, 55 ]
Above, we iterate over each element of the original array and then each number, checking if the sum of that index already existed, we just added the corresponding number to it othewise we set the corresponding num equal to it.
Advertisements