Suppose I have the following:
var ids = [1,5]
var persons = [{id:1, name:'stack'},{id:2, name:'stack2'},
{id:3, name:'stack3'},{id:4, name:'stack4'},{id:5, name:'stack5'}]
So I need from the lists of "persons" all the ones that have id: 1 and 5. You could do a "for" of persons and check if the id exists inside the "ids" array, but of course if you had 100000 people I don't think it would be very efficient, is there any other better way?
var result = []
for (var co in persons) {
if (id.indexOf(persons[co].id) > 0) {
result.add(persons[co])
}
}
Assuming you do the fetch once and then keep that list of items for a long time and you're going to have to fetch many times, it might be worth pre-processing the data and saving it to an object or a Map (not much of a difference in speed). of access) :
Another option would be to get that data already sorted, so you could do a binary search :
You could use the method
filter
to generate the list with the desired objects.According to the documentation, the method
filter()
of typeArray
, creates a new oneArray
with the elements that pass the filter condition.As for the efficiency, I couldn't tell you if it is more efficient than a loop or not
for
, it is probably exactly the same, but what is certain is that it looks more elegant.An example of how it would look:
EDITION
As @Kiko_L comments, if you use
indexOf()
it you save timemap
and the code looks more concise. For example:You can use
includes()
Translating from StackOverflow , you have different ways:
For IE9 or higher:
Mozilla :
Daniel James :
roosteronacid(broken link):
I invite you to go through the web in English and also read how do i check if an array includes an object in javascript