简体   繁体   中英

Filter two different structured arrays underscore js

I have two arrays:

array1 = [{Name: 'abc', ID: 23},{Name:'xyz', ID: 10},{Name:'def', ID: 12}];
array2 = [10,23];

Resultant array should be part of array 1 whose ID intersects with contents of array2.

Here, the result would be result = [{Name: 'abc', ID: 23},{Name: 'xyz', ID:10}] ;

Any ideas how I could achieve this using underscore js?

_.filter(array1, function(item){ return _.contains(array2, item.ID); });

You can use filter and contains .

Try it out here !

Assuming your IDs are unique:

var groupedById = _.indexBy(array1, "ID");
var filteredArray = _.map(array2, function (lookupId) {
    return groupedById[lookupId];
});

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