28

How can I check the array has empty element or not? Imagine this array,

var arr = [ 'a', 'b', , 'd'];

the arr[2] is undefined. I want to check this. If the element has empty element, return 'true' or return false. Maybe like this,

function hasEmptyElement(array){
    for (var i=0; i<array.length; i++){
        if (typeof arr[i] == 'undefined'){
          return true; 
          // and then ?
          // should I use double for loop or helper variable?
        }
    }
}

I confuse how can I do this. Please help me the clevers.

ton1
  • 7,238
  • 18
  • 71
  • 126

13 Answers13

64

As of ES2016, you should use Array.prototype.includes:

const array = ["a", "b", , "d"];
array.includes(undefined); // true

(You don't need to write undefined, but this makes it more clear what's happening.)

Note that this method treats slots valued undefined and empty slots the same, although they're not. If you need to differentiate these two cases as well, starting from ES2017, you can use Object.values making the following expression true if there are empty slots in the array:

Object.values(array).length !== array.length; // true
Chiru
  • 3,661
  • 1
  • 20
  • 30
  • 1
    Do you know why array.indexOf(undefined) is -1? – James Feb 01 '21 at 02:12
  • 1
    @James: Because the third element of `array` isn't actually `undefined`, but rather an empty slot. `Array.prototype.includes`, however, treats empty slots and slots valued `undefined` the same. – Chiru Feb 01 '21 at 07:36
  • 1
    will fail for `["a", "b", undefined, "d"]` since the third slot is not empty. – vsync Jul 21 '22 at 20:39
  • @vsync: The answer above has been pointing this out for over half a decade and even provides a solution for this edge case, have you read it? – Chiru Jul 22 '22 at 09:27
23

First, note the difference between empty slots and slots with undefined value:

var arr = [/*empty slot*/, undefined];
Object.keys(arr); // ["1"] but not "0"
"0" in arr; // false
"1" in arr; // true

ES5 array methods skip empty slots. ES6 [].includes does not.

That means you can use

arr.includes(undefined); // has empty slot OR contains undefined value
arr.indexOf(undefined) > -1; // contains undefined value

If you want to test only if there are empty slots, you can iterate manually with a for loop and check whether all indices between 0 and the length of the array are present, e.g. with in operator.

(function() {
  for(var i=0; i<arr.length; ++i) if(!(i in arr)) return true;
  return false;
})(); // has empty slot

Or you can also use ES5 array methods and check if they skipped an index.

var n = 0;
arr.some((_,i) => i !== n++); // has empty slot
Oriol
  • 274,082
  • 63
  • 437
  • 513
3

You could also use Array.prototype.findIndex()

var arr = ['a', 'b', , 'd'];

document.write(arr.findIndex(e => e === undefined) > -1);
isvforall
  • 8,768
  • 6
  • 35
  • 50
  • This solves the problem of finding the first empty or undefined index, which is the first part of my problem, though it's technically beyond the OP's question. Thanks for going one step beyond. – Sideways S May 30 '23 at 17:15
2

try

var hasAnyEmptyElement = arr.filter(function(val){ return (typeof val) != "undefined" }).length != arr.length;

DEMO

var arr = [1,2];
arr[4] = 2;

var hasAnyEmptyElement = arr.filter(function(val){ return (typeof val) != "undefined" }).length != arr.length;

alert(hasAnyEmptyElement);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

You can do something like that:

function hasEmptyElement(array){
    for (var i=0; i<array.length; i++){
        if (!(i in array)) {
            return true;
        }
    }
    return false;
}

The main point of this implementation is that it makes difference between [1,,3] and [1, undefined, 3]

Nikolai Mavrenkov
  • 1,851
  • 18
  • 21
2
var temp = arr.filter(item => item);

This will give you a new array with below elements: ["a", "b", "d"]

The above solution will help to remove empty as well as null values.

veben
  • 19,637
  • 14
  • 60
  • 80
Trish
  • 29
  • 2
  • 3
    This is unreliable because there may be items in the array such as the number 0 or the boolean false. instead use arr.filter(item => item !== undefined).length – Dylan Maxey Nov 15 '20 at 08:46
1

Simple implementation using set

var arr = [ 'a', 'b', , 'd'];
// Using Set from es6
var arraySet = new Set(arr)
arraySet.has(undefined) // returns true

Thanks!

yaswanthkoneri
  • 408
  • 4
  • 16
  • this is also showing true for: `var arr = [ 'a', 'b', undefined]; var arraySet = new Set(arr) arraySet.has(undefined) // true` – Kishor Dec 21 '19 at 16:43
0

You can try like this:

var arr = [ 'a', 'b',, 'd'];
function myfunc(arr) {
  for(var i=0; i<arr.length; i++) {
    if (!(i in arr)) return false;
  }
  return true;
}
alert( myfunc(arr));
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • I think you should edit your answer as it makes no sense and has very little information – vsync Jul 21 '22 at 20:55
0

For ES5- you can do

var arr = [ 'a', 'b', , 'd'];
arr.filter(function() { return true }).length === arr.length

That is going to return false if there is a undefined

ES2015 check includes

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
0
`Check null/undefined values in Array`

function checkNullValue(a) {
                    if (typeof (a) == 'undefined' || a === null) {
                        return false;
                    } else {
                        return true;
                    }

     }

    var arrayMonthVal = ['1','2',,'6','null', '8'];

    var pass = arrayMonthVal.some(checkNullValue);
Mujahid
  • 117
  • 1
  • 8
0

I recently needed to know if a given array element was empty and this page helped me derive the following solution:

/** Determine if an array element is empty.
 *  @param {*[]} arr
 *  @param {number} [i] If not provided, check entire arr for empty.
 *  @return {boolean}
 */
const hasEmpty = (arr, i) => 0<=i 
  ? !arr.some((_, j) => j==i) 
  : Object.values(arr).length!==arr.length;
mrwolf
  • 3
  • 4
-1

Making it simple you can use the below comparison for achieving the same.

function hasEmptyElement(array){
   for(var i=0;i<array.length;i++){
       if(my_arr[i] === "")   
          return false;
   }
   return true;
}
  • Your code says that there is an empty element if, and only if, it doesn't contain the empty string. – Oriol Apr 14 '16 at 12:52
  • yes Oriol , I accept that the user was referring to the character literal that are to be checked. And to generalise we can substitute the "" with null keyword to check for nulls that are I suppose generic to all types – user6203759 Apr 14 '16 at 14:09
  • The [null value](http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.11) belongs to the [Null type](http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.12). It's not generic. – Oriol Apr 14 '16 at 16:21
-4

hello try this....

 if (typeof arr[i] == 'NULL'){
      return true; 
}

hope this may work

dfdsf
  • 5
  • 1