maumauy
maumauy

Reputation: 25

if any item in array === x then return false

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.

Upvotes: 2

Views: 1993

Answers (5)

Trott
Trott

Reputation: 70115

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)

Upvotes: 2

AmN
AmN

Reputation: 331

a.every(function(val){
    return val == true;
});

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

Upvotes: 0

Putk0
Putk0

Reputation: 13

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.

Upvotes: 0

Carl Edwards
Carl Edwards

Reputation: 14454

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

Upvotes: 8

PekosoG
PekosoG

Reputation: 264

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

Upvotes: 0

Related Questions