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
-
Economics & Finance
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
How It Works
The function iterates through the first array and checks if each element exists in both the second and third arrays using indexOf(). When a common element is found, it removes that element from the other arrays using splice() to avoid counting duplicates, then adds it to the sum.
In our example, elements 3 and 4 are common to all three arrays, so the sum is 3 + 4 = 7.
Alternative Approach Using Set Intersection
Here's a more functional approach using Set operations:
const arr1 = [4, 4, 5, 8, 3];
const arr2 = [7, 3, 7, 4, 1];
const arr3 = [11, 0, 7, 3, 4];
const sumCommonWithSet = (arr1, arr2, arr3) => {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
const set3 = new Set(arr3);
const common = [...set1].filter(x => set2.has(x) && set3.has(x));
return common.reduce((sum, num) => sum + num, 0);
};
console.log(sumCommonWithSet(arr1, arr2, arr3));
7
Comparison
| Method | Time Complexity | Space Complexity | Modifies Original Arrays |
|---|---|---|---|
| indexOf + splice | O(n²) | O(1) | Yes |
| Set intersection | O(n) | O(n) | No |
Conclusion
Both approaches find the sum of common elements effectively. The Set-based method is more efficient and doesn't modify the original arrays, making it preferable for most use cases.
