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
Finding the sum of all common elements within arrays using JavaScript
Problem
We are required to write a JavaScript function that takes in three arrays of numbers. Our function should return the sum of all those numbers that are common in all three arrays.
Example
Following is the code −
const arr1 = [4, 4, 5, 8, 3];
const arr2 = [7, 3, 7, 4, 1];
const arr3 = [11, 0, 7, 3, 4];
const sumCommon = (arr1 = [], arr2 = [], arr3 = []) => {
let sum = 0;
for(let i = 0; i < arr1.length; i++){
const el = arr1[i];
const ind2 = arr2.indexOf(el);
const ind3 = arr3.indexOf(el);
if(ind2 !== -1 && ind3 !== -1){
arr2.splice(ind2, 1);
arr3.splice(ind3, 1);
sum += el;
};
};
return sum;
};
console.log(sumCommon(arr1, arr2, arr3));
Output
7
Advertisements
