Filter two different structured arrays underscore js

寵の児 提交于 2019-12-13 04:34:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!