简体   繁体   中英

javascript: How to compare two arrays of objects using functional programming?

So recently I was doing a node school challenge, Here's the task:

Return a function that takes a list of valid users, and returns a function that returns true if all of the supplied users exist in the original list of users.

Here's the solution:

   module.exports = function (goodUsers) {
   return function (submittedUsers) {
       return submittedUsers.every(function (submittedUser) {
           return goodUsers.some(function (goodUser) {
               return goodUser.id === submittedUser.id;
           });
       });
   };
};

Basically its a function that takes in an object of ids and compares it with another one. it returns true if if the second objects' ids are in the first object. Here's an example: http://s8.postimg.org/ql8df5iat/Screen_Shot_2014_02_01_at_5_32_07_PM.png

However I've read the MDN examples for awhile and just can't seem to understand why this solution works! Can someone walk me through step by step on what's actually happening here? Why does this work? How do the every() and some() methods handle the differences is array length? etc

-Thanks

Actually the functions every and some don't care about array length.

every will just execute an arbitrary code for each element of your first array.

some will just return true if there is at least one object with the same id' in the second array.

Note === this will "short circuit" in the case of null or undefined values.

Hope this helps.

Personally, I prefer the double “for” loop syntax as I think it is more readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM