Reputation: 1655
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'
Upvotes: 0
Views: 608
Reputation: 19070
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'));
Upvotes: 0
Reputation: 1156
use .every()
array.every(d => d.includes("morning")) // true
array.every(d => d.includes("afternoon")) //false
Upvotes: 1
Reputation: 39322
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'));
Upvotes: 3
Reputation: 28445
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
Upvotes: 2