Sparked Sparked - 5 months ago 9
Javascript Question

Compare array of objects to array of ids

Using jQuery, I would like to use an array of ids to find the objects inside the

array that have the matching

var arrayOfIds = [1, 4, 5];

var allObjects = [{"Id":"1", "name":"aa"},{"Id":"2", "name":"bb"} ,{"Id":"3", "name":"cc"} ,{"Id":"4", "name":"dd"}, {"Id":"5", "name":"ee"}, {"Id":"6", "name":"ff"}, {"Id":"7", "name":"gg"}, {"Id":"8", "name":"hh"}, {"Id":"9", "name":"ii"}];

The result would equal:

[{"Id":"1", "name":"aa"}, {"Id":"4", "name":"dd"}, {"Id":"5", "name":"ee"}]

So far, I can only use the following to extract an individual object:

var result = $.grep(arrayOfIds, function(e) { return e.Id == 3; });

I feel as though the answer might be achieved by amending the above $.grep query somehow but can't figure it out.


You don't need jQuery for this. You can use Array.prototype.filter() to filter allObjects and Array.prototype.includes() to check if the objects Id property is in arrayOfIds:

allObjects.filter(x=> arrayOfIds.includes(Number(x.Id)))

See demo on JS Bin.