简体   繁体   中英

Filtering an array with an array of values

I have 2 arrays and i'd like to filter one array with the other. Eg if array1 includes any of the values in array2, they should be returned.

The two arrays are:

const array1 = [a, b, c, d]

The other array, which should be filtered where 'id' is equal to any of the values in array1 is:

const array2 = [
{
   id: b
   title: title1
},
{
   id: d
   title: title2
},
{
   id: f
   title: title3
}
]

The easiest way is to use two for-loops. Possible not the fastest approach.

res = [];
for (var i = 0;i<array1.length;i++) {
    for (var j = 0;j<array2.length;j++) {
        if (array1[i] == array2[j].id) {
            res.push(array2[j]);
             break;
        }
    } 
}

You could use Array.prototype.filter() and Array.prototype.indexOf() :

const array1 = ['a', 'b', 'c', 'd'];

const array2 = [{
   id: 'b',
   title: 'title1'
}, {
   id: 'd',
   title: 'title2'
}, {
   id: 'f',
   title: 'title3'
}];

const result = array2.filter(function(x){
    return array1.indexOf(x.id) !== -1;
});

Adding this missing '' , You can use filter and includes methods of Array.

const array1 = ['a', 'b', 'c', 'd'];
const array2 = [
    {
       id: 'b',
       title: 'title1'
    },
    {
       id: 'd',
       title: 'title2'
    },
    {
       id: 'f',
       title: 'title3'
    }
]

const result = array2.filter(({id}) => array1.includes(id));
console.log(result);

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