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 −

 Live Demo

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

Updated on: 21-Apr-2021

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements