简体   繁体   中英

Javascript, filtering array with an array

I need to filter an array1, with each element in my array 2. Both arrays can have a random number of elements.

 array1 = [1,2,3,4,5];
 array2 = [1,3,5];
 filteredArray = [];

 array2.forEach(function(x){
   filteredArray = array1.filter(function(y){
     return y !== x;
   });
 });
 return filteredArray;
 //should return -> [2,4]
 // returns [1,2,3,4]

How can I filter an array with all elements in another array?

use arrays indexOf method

var array1 = [1,2,3,4,5];
var array2 = [1,3,5];
var filteredArray = array1.filter(function(x) {
    return array2.indexOf(x) < 0;
});

or, for sexy people, use !~ with indexOf

var array1 = [1,2,3,4,5];
var array2 = [1,3,5];
var filteredArray = array1.filter(function(x) {
    return !~array2.indexOf(x);
});

A much simpler way would be:

var filteredArray = array1.filter(function(item) {
    return !(array2.indexOf(item) >= 0);
});

 array1 = [1, 2, 3, 4, 5]; array2 = [1, 3, 5]; filteredArray = []; filteredArray = array1.filter(function (y) { return array2.indexOf(y) < 0; }); console.log(filteredArray); 

You can use indexOf() to check if the array2 item is in array1 then only add it to filteredArray if it is:

 array1 = [1,2,3,4,5];
 array2 = [1,3,5];
 filteredArray = [];

 array2.forEach(function(x){
     if (array1.indexOf(array2[x] > -1) {
         filteredArray.push(array2[x]);
     }
 });
 return filteredArray;

In ES6, you could use Set for it.

 var array1 = [1, 2, 3, 4, 5], array2 = [1, 3, 5], filteredArray = array1.filter((set => a => !set.has(a))(new Set(array2))); console.log(filteredArray); 

All indexOf no play makes me a dull boy...

 var array1 = [1,2,3,4,5], array2 = [1,3,5], filtered = array1.filter(e => !array2.includes(e)); console.log(filtered); 

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