Blog

Using JavaScript Push Common Numbers from Two Arrays into a Third Array
Posted on July 31, 2015 in Algorithms, JavaScript by Matt Jennings

function commonIdsFromTwoArrays(arr1, arr2) {
  // Array to push common IDs into
  var commonIdsArr = [];
  
  // Use a for in loop to iterate through
  // elements in "arr1" and "i" starts off as "0" and
  // increments all the way to "2" as "array1" which is passed in as the
  // "arr1" parameter goes up to index 2
  for(var i in arr1) {
    
    // Use a for loop to through all elements in 
    // "arr2" and "j" starts off as "0" and goes up to
    // "4" as the "array1" variable which is passed
    // as the "arr2" parameter goes up to index 4
    for(var j in arr2) {
      
      // The IF STATEMENT makes the following comparisons:
      // if(arr1[0] === arr2[0])
      // if(arr1[0] === arr2[1])
      // ...
      // if(arr1[0] === arr2[4])
      // if(arr1[1] === arr2[0])
      // if(arr1[1] === arr2[1])
      // ...
      // FINAL COMPARISON: if(arr1[2] === arr2[4])
      if(arr1[i] === arr2[j]) {
        
        // If the comparison above is true
        // push the "arr[i]" element into
        // the "commonIdsArr" array
        commonIdsArr.push(arr1[i]);  
      }  
    }  
  }
  
  // Return the "commonIdsArr" and sort it
  return commonIdsArr.sort();
}

var array1 = [50, 2, 102];
var array2 = [42, 5, 10, 2, 50];

// Output below is:
// [2, 50]
console.log(commonIdsFromTwoArrays(array1, array2));

Leave a Reply