3

Hi I have an array like: [null,null,null,null] in javascript. How can I know if the array has all values equal to null without iterating over it?

7
  • 3
    searching an array is O(n) Commented Sep 9, 2015 at 0:48
  • just checking if there is a JS trick or shortcut to identify null array. Commented Sep 9, 2015 at 0:50
  • 3
    Avoiding iteration is impossible. If you don't loop over the array yourself, whatever method you call will have to. Is that your goal, to avoid explicitly looping over it yourself? That's possible. Commented Sep 9, 2015 at 0:50
  • Yep that is my goal. To avoid manual iteration. Code look ugly if i do that. Commented Sep 9, 2015 at 0:51
  • 1
    @Brendan - Or better yet for(var i = 0; i < arr.length; i++) if(array[i] !== null) allNull = false; Commented Sep 9, 2015 at 1:04

2 Answers 2

6

There is no way to check for all null values, you would have to iterate over it, or the function you call will have to in the background. However, if you want, you could use the native Array method filter to help you out.

var allNull = !arr.filter(Boolean).length;

This will work with any falsy value, like undefined, zero, NaN, or an empty string. A more precise form is

var allNull = !arr.filter(function(elem){ return elem !== null; }).length;

Which would check for only null.

Another possibility is using .join:

var allNull = !arr.join("").length;

This checks for null, undefined, or ""

Sign up to request clarification or add additional context in comments.

Comments

4

There are various built–in methods to help, one is every to test that every value isn't null. It will return false at the first null:

var noNulls = array.every(function(value){return value !== null});

Another is some, which will return true at the first null:

var hasNulls = array.some(function(value){return value === null});

1 Comment

every is indeed a helpful method. I didn't even remember it existed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.