0

I have the following array

// Exmaple
[
   ['morning', 'afternoon'],
   ['morning'],
   ['morning', 'afternoon'],
   ['morning', 'afternoon'],
   ['morning']
]

I may have the same one but with afternoon in every array. I need to check if a given value exists in all arrays, for example if I check for 'morning' it should return true, but if I check for 'afternoon' it should return false because in the example array above not all of them have 'afternoon'

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
Angel Miladinov
  • 1,596
  • 4
  • 20
  • 43
  • Possible duplicate: https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript?rq=1 – Tân Nov 06 '18 at 09:54

5 Answers5

5
  array.every(day => day.includes("morning")) // true
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
3

You can use .every() and .includes() methods:

let data = [
   ['morning', 'afternoon'],
   ['morning'],
   ['morning', 'afternoon'],
   ['morning', 'afternoon'],
   ['morning']
];

let checker = (arr, str) => arr.every(a => a.includes(str));

console.log(checker(data, 'morning'));
console.log(checker(data, 'afternoon'));
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
2

You can use Array.every and Array.includes

let arr = [['morning', 'afternoon'],['morning'],['morning', 'afternoon'],['morning', 'afternoon'],['morning']];

console.log(arr.every(v => v.includes('morning'))); // true
console.log(arr.every(v => v.includes('afternoon'))); // false
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1
use .every()

 array.every(d => d.includes("morning")) // true
 array.every(d => d.includes("afternoon")) //false
Sooriya Dasanayake
  • 1,106
  • 1
  • 7
  • 14
0

You can use Array.prototype.every() and coerces to boolean the result of Array.prototype.find() which returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

Code:

const data = [['morning', 'afternoon'],['morning'],['morning', 'afternoon'],['morning','afternoon'],['morning']];
const checker = (arr, str) => arr.every(a => !!a.find(a => str === a));

console.log(checker(data, 'morning'));
console.log(checker(data, 'afternoon'));
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46