0

I'm trying to avoid multiple logical OR conditional checks with || using includes. Could anyone please help how to achieve that using array's include method?

const cars = [{
  name: 'BMW',
  year: '2020'
}, {
  name: 'Audi',
  year: '2019'
}, {
  name: 'Benz',
  year: '2018'
}]

const result = cars.includes(['BMW', 'Audi'])

console.log(result);
scriobh
  • 868
  • 10
  • 25
  • So you expect `result` to be `true` if there is at least one array element with the name "BMW" or "Audi"? `Array#includes` can't do that. – str Jun 29 '20 at 16:07

1 Answers1

0

You can use some for this. In your case even twice:

const cars = [{
  name: 'BMW',
  year: '2020'
}, {
  name: 'Audi',
  year: '2019'
}, {
  name: 'Benz',
  year: '2018'
}]


const result = ['BMW', 'Audi'].some((searchedName) => cars.some((car) => car.name === searchedName));

console.log(result);

This is not a solution with a focus on performance but rather a focus on avoiding ||.

Benjamin Eckardt
  • 709
  • 6
  • 10
  • Great! How do i get the objects in from the array which are found. That is, `[{ name: 'BMW', year: '2020' }, { name: 'Audi', year: '2019' }]` – scriobh Jun 29 '20 at 18:23
  • Could you please let me know how do i return the values instead of boolean result? @Benjamin – scriobh Jun 29 '20 at 18:29
  • Please try yourself. It's really not that hard. Little hint: you need to shuffle the code a but and use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter instead of `some` in one place. – Benjamin Eckardt Jun 30 '20 at 08:59
  • BTW: This question was closed referencing an entry that should apply to your case. – Benjamin Eckardt Jun 30 '20 at 09:00