Comparing and Filtering two arrays
Asked Answered
S

10

22

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!

Spy answered 22/5, 2015 at 6:16 Comment(3)
In php you could use array_intersect, but your code seems a bit like JSQualm
possible duplicate of Simplest code for array intersection in javascriptCircumstantiality
Is the order of elements in result array2 important to you?Protium
G
30

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);
Gilda answered 6/10, 2015 at 4:34 Comment(1)
With ES6 arr1.filter(e => arr2.includes(e)).Gilda
W
2

You can use some, like this:

let newArray = array2.filter(
      (array22) => !array1.some((array11) => array11.id === array22._id));
Wick answered 14/6, 2022 at 11:2 Comment(0)
E
1

Hi this is a porting of the function array_intersect php. Should be good for you http://phpjs.org/functions/array_intersect/

function array_intersect(arr1) {
  //  discuss at: http://phpjs.org/functions/array_intersect/
  // original by: Brett Zamir (http://brett-zamir.me)
  //        note: These only output associative arrays (would need to be
  //        note: all numeric and counting from zero to be numeric)
  //   example 1: $array1 = {'a' : 'green', 0:'red', 1: 'blue'};
  //   example 1: $array2 = {'b' : 'green', 0:'yellow', 1:'red'};
  //   example 1: $array3 = ['green', 'red'];
  //   example 1: $result = array_intersect($array1, $array2, $array3);
  //   returns 1: {0: 'red', a: 'green'}

  var retArr = {},
    argl = arguments.length,
    arglm1 = argl - 1,
    k1 = '',
    arr = {},
    i = 0,
    k = '';

  arr1keys: for (k1 in arr1) {
    arrs: for (i = 1; i < argl; i++) {
      arr = arguments[i];
      for (k in arr) {
        if (arr[k] === arr1[k1]) {
          if (i === arglm1) {
            retArr[k1] = arr1[k1];
          }
          // If the innermost loop always leads at least once to an equal value, continue the loop until done
          continue arrs;
        }
      }
      // If it reaches here, it wasn't found in at least one array, so try next value
      continue arr1keys;
    }
  }

  return retArr;
}
Epicycle answered 22/5, 2015 at 7:2 Comment(0)
D
1

You can use

const arr1 = [1, 2, 3];
const arr2 = [2, 3];

arr1.filter(e => arr2.indexOf(e) > -1 ? false : true); // [1]
Diedra answered 11/10, 2021 at 14:44 Comment(0)
O
1

Came here some week back to find a solution to a problem like this but its a pity I couldn't get what I wanted, but now I figured it out in a more simple way. using the arrow function, .filter() method and .includes() method.

Declare an arrow function that takes in two arguments:

const filterTwoArrays = (string1, string2) => string1.filter(item => string2.includes(item));

console.log(filterTwoArrays(array1, array2)).
Oneirocritic answered 8/5, 2022 at 11:4 Comment(0)
C
0
const arr1 = [1, 2, 3];
const arr2 = [2, 3]; 
const finalArray = arr1.filter(person => arr2.some(person2 => person.includes(person2)))
Circinus answered 22/5, 2015 at 6:17 Comment(0)
M
0

Since you have tagged javascript here is the solution.

function f1(x, y) {
    var t = y.slice(0);
    var r = [];
    for (var i = 0; i < x.length; i++) {
        for (var j = 0; j < y.length; j++) {
            if (x[i] === y[j]) {
                [].push.apply(r, t.splice(j, 1));
            }
        }
    }
    console.log(r)
    y.length = 0;
    [].push.apply(y, r);
}
Mani answered 22/5, 2015 at 7:6 Comment(0)
M
0

Here is one simple way based on your code

function array_filter(filter, result) {
    var filterLen = filter.length;
    var resultLen = result.length;

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

//Return boolean depending if array 'a' contains item 'obj'
function contains(array, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] == value) {
            return true;
        }
    }
    return false;
}
Mcginnis answered 22/5, 2015 at 7:14 Comment(0)
B
0

Mark the items which are to be filtered out via delete result[index] manipulate them as needed.

JavaScript

window.onload = runs;

function runs() {
    var array1 = ["apples", "grapes", "oranges"];
    var array2 = ["potato", "pears", "grapes", "berries", "apples", "oranges"];
    var result = filter_twoArrays(array1, array2);

    function filter_twoArrays(filter, result) {
        var i = 0,
            j = 0;
        for (i = 0; i < result.length; i++) {
            var FLAG = 0;
            for (j = 0; j < filter.length; j++) {
                if (filter[j] == result[i]) {
                    FLAG = 1;
                }
            }
            if (FLAG == 0) delete result[i];
        }
        return result;
    }

    var body = document.getElementsByTagName("body")[0];
    var i = 0;
    for (i = 0; i < result.length; i++) {
        if (result[i] !== undefined)
            body.innerHTML = body.innerHTML + result[i] + " ";
    }
}
Baro answered 22/5, 2015 at 7:14 Comment(0)
V
0

const func = array1.filter(item => array2.includes(item));

Versieversification answered 8/12, 2022 at 18:6 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Scaliger

© 2022 - 2024 — McMap. All rights reserved.