Comparing and Filtering two arrays

Alejandro picture Alejandro · May 22, 2015 · Viewed 42.3k times · Source

I've been trying to implement a function where given with two arrays,

array1's elements is used as conditions to filter out elements in array2.

For instance:

array1= [apple, grapes, oranges]

array2= [potato, pears, grapes, berries, apples, oranges]

After feeding into a function, array2 should have elements as such:

filter_twoArrays(array1,array2)

array2= [grapes, apples, oranges]

I've tried the following code, using for loops and array.splice(), but the problem I am seeing is that when I use the splice method, it seems that it changes the lengths of array2 in the for loop:

function filter_twoArrays(filter,result){

  for(i=0; i< filter.length; i++){
    for(j=0; j< result.length; j++){
      if(filter[i] !== result[j]){
        result.splice(j,1)
      }
    }
  }

Any inputs will be greatly appreciated on how to refine the filter function

cheers!

Answer

Tushar picture Tushar · Oct 6, 2015

You can use filter as follow

var array1 = ['apples', 'grapes', 'oranges', 'banana'],
  array2 = ['potato', 'pears', 'grapes', 'berries', 'apples', 'oranges'];

var intersection = array1.filter(function(e) {
  return array2.indexOf(e) > -1;
});

console.log(intersection);

You can also add this method on Array prototype and call it directly on array

Array.prototype.intersection = function(arr) {
  return this.filter(function(e) {
    return arr.indexOf(e) > -1;
  });
};

var array1 = ['apples', 'grapes', 'oranges', 'banana'],
  array2 = ['potato', 'pears', 'grapes', 'berries', 'apples', 'oranges'];

var intersection = array1.intersection(array2);
console.log(intersection);