Skip to content Skip to sidebar Skip to footer

Filtering An Array Of Objects From An Array Of Strings

I have an array of Strings var allEmojis = [dog, toucan, flamingo, lion, tiger, duck, elephant, zebra]and an array of objects as displayed that I obtained from mongoose. Each obje

Solution 1:

You wrote your allEmojis without quotes

var allEmojis  = [dog, toucan, flamingo, lion, tiger, duck, elephant, zebra]

Array of strings would be

var allEmojis  = ["dog", "toucan", "flamingo", "lion", "tiger", "duck", "elephant", "zebra"]

If this is not a problem and allEmojis really contains a strings, which are in arrayOfObjects in every object under key object.emoji, then you can filter intersection of allEmojis with arrayOfObjects like so

var filtered = allEmojis.filter(function(e) {
    return !!arrayOfObjects.find(function(o) {
        return o.emoji === e;
    });
};

You can also write it as

var filtered = arrayOfObjects
    .filter(function(o) { return allEmojis.includes(o.emoji) })
    .map(function(o) { return o.emoji }); // convert objects to strings

which probably has better performance.

Post a Comment for "Filtering An Array Of Objects From An Array Of Strings"