问题
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?
回答1:
_.filter(array1, function(item){ return _.contains(array2, item.ID); });
You can use filter and contains.
Try it out here!
回答2:
Assuming your IDs are unique:
var groupedById = _.indexBy(array1, "ID");
var filteredArray = _.map(array2, function (lookupId) {
return groupedById[lookupId];
});
来源:https://stackoverflow.com/questions/21617600/filter-two-different-structured-arrays-underscore-js