Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

javascript - 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 object in the array of objects has the attribute emoji which is filtered from the allEmojis array. (Below is the array of objects)

enter image description here

I would like to filter the array like so:

let's assume that the array of objects is simply: 'ArrayOfObjects'

 var JohnsEmojis = allEmojis.filter(function(emoji) {
  return !ArrayOfObjects.includes(emoji) /*=>>> where the object in ArrayOfObjects
    containing the emoji has an id of John not yoyoyo (yes i know, dumb name); */ 
  }) 

 var yoyoyoEmojis = allEmojis.filter(function(emoji) {
  return !ArrayOfObjects.includes(emoji) /*=>>> where the object in ArrayOfObjects
    containing the emoji has an id of yoyoyo not John; */ 
  })  

My code fails on two counts. You cannot use the include on an array of objects with an array of string. Also assuming this did work, it does not filter based on the objects that have the specified id. I was hoping I could find the most efficient way to do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...