简体   繁体   中英

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!

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);

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;
}

You can use some , like this:

let newArray = array2.filter(
      (array22) => !array1.some((array11) => array11.id === array22._id));

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);
}

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;
}

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] + " ";
    }
}

You can use

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

arr1.filter(e => arr2.indexOf(e) > -1 ? false : true); // [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)).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM