Reputation: 12838
I'm basically creating a getItemsByIds(ids)
function where items
is an array of objects, each having an id
key, and ids
an array of ids.
I'm newish to ES6 so I'm sure there's a more elegant way to solve this, and since all my services will have this type of function I'd like it to be as optimal as possible. Here's what I have now:
getItemsByIds (ids) {
return this.getAllItems().then(items => items.filter(item => {
for (var i = 0; i < ids.length; i++) {
if (item.id == ids[i]) {
return true;
}
}
return false;
}));
}
And like I said, the items
array is basically this:
[{id: 0, name: 'Foo'}, {id: 1, name: 'Bar'}, {id: 2, name: 'Baz'}]
Upvotes: 2
Views: 53
Reputation: 27247
An alternative to Array#indexOf
, if available to you (e.g. polyfilled), is the ES2016 method Array#includes
.
getItemsByIds (ids) {
return this.getAllItems()
.then(items => items.filter(item => ids.includes(item.id));
}
Upvotes: 2
Reputation: 490273
You could turn it into ids.indexOf(item.id) > -1
.
getItemsByIds (ids) {
return this.getAllItems()
.then(items => items.filter(item => ids.indexOf(item.id) > -1));
}
Upvotes: 2