Javascript check if all arays contain the same value

3570 views javascript
2

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'

answered question

5 Answers

5

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

posted this
0

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

posted this
2

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'));

posted this
13

use .every()

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

posted this
5

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

function checkInput(str, arr){
  var flag = true;
  for(var i = 0; i< arr.length; i++){
    var count = arr[i].filter(j => j==str).length;
    if(count == 0){
      flag = false;
    }
  }
  return flag;
}

console.log(checkInput('morning', arr))
console.log(checkInput('afternoon', arr))

posted this

Have an answer?

JD

Please login first before posting an answer.