0
var array = [false,true,true,true,true];

I would like to return false if any item in array is false and only return true if all items are true. is there a fast way to do this with out all the boilerplate? in python i would use the "if is in" syntax.

maumauy
  • 5
  • 1
  • 3
  • Possible duplicate of [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – ubadub Dec 23 '17 at 23:56

5 Answers5

6

In your case you'd use the every() method. The method expects every return value in each iteration to evaluate to true so simply passing the current value, which all happen to be a booleans will suffice without any additional logic.

var array = [false, true, true, true, true].every(bool => bool);

console.log(array);
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119
2

Option 1: You can use .indexOf(). This example will return false if myArray contains false, and return true otherwise:

function hasNoFalse(myIndex) {
  return myArray.indexOf(false) === -1;
}

Option 2: You can use .some() or .every() :

I would like to return false if any item in array is false

return myArray.some((val) => val === false)

and only return true if all items are true.

return myArray.every((val) => val === true)
Trott
  • 66,479
  • 23
  • 173
  • 212
  • *"If you need to avoid ES6 stuff, you can use .indexOf()"* – I don't think you'll run into compatibility issues given, `every()` was implemented in ES5 – Carl Edwards Dec 23 '17 at 23:57
  • @CarlEdwards Good point. Not many people are in ES3-only environments. :-D I'll change the text.... – Trott Dec 24 '17 at 00:29
  • `.some()` is nice as it is symmetrical with `.every()` and lexically self-documenting whereas `indexOf()` seems a bit obtuse. – Shanerk Oct 06 '22 at 19:55
0

you can use .indexOf(element) and if the result is greater than -1, then there's that element in the array

PekosoG
  • 246
  • 3
  • 9
0
a.every(function(val){
    return val == true;
});

Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

AmN
  • 331
  • 1
  • 7
  • @Intervalia I am no javascript expert. But I dont think a correct answer deserves a downvote even if it is a slow one. – AmN Dec 23 '17 at 23:52
0

While everyone is using arrow function, this is one way to do it without it

function myFunction(array) {
var b = 0;
array.forEach(function(element) {

    if(element)
        b++
});
if(b == array.length)
    return true;
else 
    return false;
}

I wrote this only for people who don't know what arrow is.

Putk0
  • 13
  • 3