Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing and Filtering two arrays

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!

like image 578
Alejandro Avatar asked May 22 '15 06:05

Alejandro


People also ask

How do I compare two arrays of arrays?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

How do you compare two data arrays?

equals() Method. Java Arrays class provides the equals() method to compare two arrays. It iterates over each value of an array and compares the elements using the equals() method.

How do you compare two arrays to find matches?

JavaScript finding non-matching values in two arrays The code will look like this. const array1 = [1, 2, 3, 4, 5, 6]; const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const output = array2. filter(function (obj) { return array1. indexOf(obj) === -1; }); console.


1 Answers

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);
like image 107
Tushar Avatar answered Sep 22 '22 17:09

Tushar