0

I have the following array

let registrations = [
   {user:1, reg_on:'12/02/2009'},
   {user:10, reg_on:'11/02/2009'},
   {user:5, reg_on:'11/02/2109'},
     ///others
 ]

So now am trying to find one record where user is 1 or 5 thats the first

SO i have done the following which works

let final =  registrations.find(reg=>reg.user === 1 ||reg.user === 5);

The above works but it becomes tedious if there is a need to add more filter parameters like reg.user === 10

So i have tried refactoring this like

 let final =  registrations.find(reg=>reg.user.includes([1,5,10]));

But now the one having includes doesnt work. What am i missing out?

Geoff
  • 6,277
  • 23
  • 87
  • 197
  • Possible duplicate of [JavaScript: Simple way to check if variable is equal to two or more values?](https://stackoverflow.com/questions/12116326/javascript-simple-way-to-check-if-variable-is-equal-to-two-or-more-values) – Heretic Monkey Sep 02 '19 at 23:18
  • Your includes is backwards. – epascarello Sep 02 '19 at 23:51
  • @HereticMonkey the answer youve provided is different from my scope, In my question i have specified that am interested in using includes, the answer youve provided uses indexOf, and also it also recommends using what am doing but my question is about refactoring the code. – Geoff Sep 03 '19 at 00:34
  • Then [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/q/237104/215552) is the appropriate duplicate... – Heretic Monkey Sep 03 '19 at 01:13
  • You can have a set of allowed user and than use `allowedUser.has(reg.user)` – Code Maniac Sep 03 '19 at 01:31

1 Answers1

7

Make an array of user numbers to find, and check whether it .includes the reg.user:

registrations.find(reg => [1, 5, 10].includes(reg.user));

let registrations = [
   {user:1, reg_on:'12/02/2009'},
   {user:10, reg_on:'11/02/2009'},
   {user:5, reg_on:'11/02/2109'},
     ///others
];

let final = registrations.find(reg => [1, 5, 10].includes(reg.user));

console.log(final);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320