powerbuoy
powerbuoy

Reputation: 12838

Most elegant way to filter array by other array

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

Answers (2)

sdgluck
sdgluck

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

alex
alex

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

Related Questions