Angel Miladinov
Angel Miladinov

Reputation: 1655

JavaScript: Check if all arrays contain same value?

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

Answers (5)

Yosvel Quintero
Yosvel Quintero

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

Sooriya Dasanayake
Sooriya Dasanayake

Reputation: 1156

use .every()

 array.every(d => d.includes("morning")) // true
 array.every(d => d.includes("afternoon")) //false

Upvotes: 1

Mohammad Usman
Mohammad Usman

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

Nikhil Aggarwal
Nikhil Aggarwal

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

Jonas Wilms
Jonas Wilms

Reputation: 138247

  array.every(day => day.includes("morning")) // true

Upvotes: 5

Related Questions