-1

I require to return either true or false on a conditional basis. If my array contains a empty, null, undefined,"" I require to return false. else true.

Is there any easy and correct way to return like ?

Here is what I am looking for :

var ar = ["apple", '', undefined, null ]; //false
var ar = ["apple", 'Orange', undefined, null ]; //false
var ar = ["apple", 'Orange', "gova", null ]; //false

var ar = ["apple", 'Orange', "gova", "mango" ]; //true

How to find the falsy and truthy?

Krishna Prashatt
  • 631
  • 9
  • 18
user2024080
  • 1
  • 14
  • 56
  • 96
  • Possible duplicate of [Is there a standard function to check for null, undefined, or blank variables in JavaScript?](https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in) – Fabio_MO May 25 '18 at 09:38
  • why down vote here? – user2024080 May 25 '18 at 09:40

3 Answers3

5

You can use Array.prototype.some to check if there is at least one falsy element in it. Then negating the result should get you what you want.

var ar = ["apple", 'Orange', "gova", null ]; //false
console.log(!ar.some(t => !t));
ar = ["apple", 'Orange', "gova", "mango" ]; //true
console.log(!ar.some(t => !t));
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
3
!ar.some(element => !element);

Explained:

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

The expression !element coerces the value to a boolean, so falsy elements become true and truthy elements become false.

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

Máté Safranka
  • 4,081
  • 1
  • 10
  • 22
0

You could check every item with Boolean as callback for all truthy elements.

function check(array) {
    return array.every(Boolean);
}

var array = [["apple", '', undefined, null], ["apple", 'Orange', undefined, null], ["apple", 'Orange', "gova", null ], ["apple", 'Orange', "gova", "mango"]];

console.log(array.map(check));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392