20

I need to check if array contains at least one empty elements. If any of the one element is empty then it will return false.

Example:

var my_arr = new Array(); 
my_arr[0] = ""; 
my_arr[1] = " hi ";
my_arr[2] = "";

The 0th and 2nd array elements are "empty".

8
  • By empty do you mean undefined or empty strings? Commented Aug 11, 2010 at 11:35
  • var my_arr = new Array(); my_arr[0] = ""; my_arr[1] = " hi "; my_arr[2] = ""; here the 0th and 2nd element is empty Commented Aug 11, 2010 at 11:36
  • Is this a Java question or a javascript question? These are completely unrelated. Oh, and now it looks like PHP with all those $ signs. Make up your mind... Commented Aug 11, 2010 at 11:36
  • 2
    santanu, The code you just posted is PHP. Not JavaScript. Commented Aug 11, 2010 at 11:37
  • 2
    @santanu: I converted your code to JavaScript and added it to your question. Commented Aug 11, 2010 at 11:38

18 Answers 18

22

You can check by looping through the array with a simple for, like this:

function NoneEmpty(arr) {
  for(var i=0; i<arr.length; i++) {
    if(arr[i] === "") return false;
  }
  return true;
}

You can give it a try here, the reason we're not using .indexOf() here is lack of support in IE, otherwise it'd be even simpler like this:

function NoneEmpty(arr) {
  return arr.indexOf("") === -1;
}

But alas, IE doesn't support this function on arrays, at least not yet.

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

6 Comments

Isn't this the reverse of what the OP asked for (returns true if the array has only empty elements, instead of returns false if any element is empty)?
Good call on the indexOf for array's. Now just let's hope someone from the IE dev team reads this and fix it !
@Telemachus - Good catch, I missed his explicit "which result is false" requirement, updated :)
Wouldn't it be better if we make isEmpty function the second parameter of HasEmpty, and the arr[i] === "" implementation as default.
FWIW, which probably isn't much until we can drop support for <IE8, IE9 will support indexOf() and the other ECMAScript 5th array functions. blogs.msdn.com/b/ie/archive/2010/06/25/…
|
17

You have to check in through loop.

function checkArray(my_arr){
   for(var i=0;i<my_arr.length;i++){
       if(my_arr[i] === "")   
          return false;
   }
   return true;
}

Comments

8

You can try jQuery.inArray() function:

return jQuery.inArray("", my_arr)

4 Comments

Including jQuery for this seems just a bit overkill, don'tcha think?
@Nick Craver - yes, overkill if this is the only reason for using jQuery. On the other hand, when using jQuery this is a good solution :-)
@Vitalii - Sometimes it's used, it's still a minority, my point was you should qualify this type of answer on a question not tagged jQuery with something like "If you're already using jQuery..." A novice finding this later and including jQuery for just this would be a bad thing.
@Vitalii - I think you misunderstood, I meant a JS novice, not an SO one. By definition, they don't know what's best :)
5

Using a "higher order function" like filter instead of looping can sometimes make for faster, safer, and more readable code. Here, you could filter the array to remove items that are not the empty string, then check the length of the resultant array.

Basic JavaScript

var my_arr = ["", "hi", ""]

// only keep items that are the empty string
new_arr = my_arr.filter(function(item) {
  return item === ""
})

// if filtered array is not empty, there are empty strings
console.log(new_arr);
console.log(new_arr.length === 0);

Modern Javascript: One-liner

var my_arr = ["", "hi", ""]
var result = my_arr.filter(item => item === "").length === 0
console.log(result);

A note about performance

Looping is likely faster in this case, since you can stop looping as soon as you find an empty string. I might still choose to use filter for code succinctness and readability, but either strategy is defensible.

If you needed to loop over all the elements in the array, however-- perhaps to check if every item is the empty string-- filter would likely be much faster than a for loop!

Comments

4

Nowadays we can use Array.includes

my_arr.includes("")

Returns a Boolean

Comments

3

You could do a simple help method for this:

function hasEmptyValues(ary) {
    var l = ary.length,
        i = 0;

    for (i = 0; i < l; i += 1) {
        if (!ary[i]) {
            return false;
        }
    }

    return true;
}

//check for empty
var isEmpty = hasEmptyValues(myArray);

EDIT: This checks for false, undefined, NaN, null, "" and 0.

EDIT2: Misread the true/false expectation.

..fredrik

Comments

3
function containsEmpty(a) {
    return [].concat(a).sort().reverse().pop() === "";
}
alert(containsEmpty(['1','','qwerty','100'])); // true
alert(containsEmpty(['1','2','qwerty','100'])); // false

Comments

2
my_arr.includes("")

This returned undefined instead of a boolean value so here's an alternative.

function checkEmptyString(item){
     if (item.trim().length > 0) return false;
     else return true;
    };
    
function checkIfArrayContainsEmptyString(array) {
  const containsEmptyString = array.some(checkEmptyString);
  return containsEmptyString;
};
    
console.log(checkIfArrayContainsEmptyString(["","hey","","this","is","my","solution"]))
// *returns true*

console.log(checkIfArrayContainsEmptyString(["yay","it","works"]))
// *returns false*

Comments

2
yourArray.join('').length > 0

Join your array without any space in between and check for its length. If the length, turns out to be greater than zero that means array was not empty. If length is less than or equal to zero, then array was empty.

1 Comment

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
1

I see in your comments beneath the question that the code example you give is PHP, so I was wondering if you were actually going for the PHP one? In PHP it would be:

function hasEmpty($array)
{
  foreach($array as $bit)
  {
    if(empty($bit)) return true;
  }

  return false;
}

Otherwise if you actually did need JavaScript, I refer to Nick Craver's answer

Comments

1

Just do a len(my_arr[i]) == 0; inside a loop to check if string is empty or not.

Comments

1

You have to check in through the array of some functions.

if isEmptyValue is true that means the array has an empty string otherwise not.

const arr=['A','B','','D'];

const isEmptyValue = arr.some(item => item.trim() === '');

console.log(isEmptyValue)

Comments

1
const hasEmptyString = (arr) => arr.includes('');

Comments

0
var containsEmpty = !my_arr.some(function(e){return (!e || 0 === e.length);});

This checks for 0, false, undefined, "" and NaN. It's also a one liner and works for IE 9 and greater.

Comments

0

One line solution to check if string have empty element

let emptyStrings = strArray.filter(str => str.trim().length <= 0);

let strArray = ['str1', '', 'str2', ' ', 'str3', '    ']
let emptyStrings = strArray.filter(str => str.trim().length <= 0);
console.log(emptyStrings)

One line solution to get non-empty strings from an array

let nonEmptyStrings = strArray.filter(str => str.trim().length > 0);

let strArray = ['str1', '', 'str2', ' ', 'str3', '    ']
let nonEmptyStrings = strArray.filter(str => str.trim().length > 0);
console.log(nonEmptyStrings)

Comments

0

If you only care about empty strings then this will do it:

const arr = ["hi","hello","","jj"]
('' in arr) //returns false

the last line checks if an empty string was found in the array.

Comments

0

I don't know if this is the most performant way, but here's a one liner in ES2015+:

// true if not empty strings
// false if there are empty strings
my_arr.filter(x => x).length === my_arr.length

The .filter(x => x) will return all the elements of the array that are not empty nor undefined. You then compare the length of the original array. If they are different, that means that the array contains empty strings.

Comments

-2

array.includes("") works just fine.

Let a = ["content1", "" , "content2"]; console.log(a.includes(""));

//Output in console true

1 Comment

This solution has already been posted: stackoverflow.com/a/63144056/2227743

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.