0

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
  • Can you post your code so far? What didn't work? How did you attempt to solve the problem? Commented Feb 7, 2014 at 1:25

2 Answers 2

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

You can use filter and contains.

Try it out here!

Sign up to request clarification or add additional context in comments.

2 Comments

Any other way? I am still not getting my result, it returns empty array.
I was missing a parenthesis. I added a jsfiddle. It works now.
1

Assuming your IDs are unique:

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

1 Comment

Note that this will return the items in the same order as the list of IDs you're requesting (i.e., the same order as specified by array2). If you would prefer that the ordering in array1 be preserved, you'll want to use a _.filter-based approached.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.