Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check JavaScript arrays for empty strings?

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".

like image 280
Santanu Avatar asked Aug 11 '10 11:08

Santanu


People also ask

How do you check if an array of strings is empty?

To check if an array is empty or not, you can use the .length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.

How check string is empty in JavaScript?

Use the length property to check if a string is empty, e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then it's empty, otherwise it isn't empty.

How do you check if an array contains an empty value?

To check if an array contains empty elements call the includes() method on the array, passing it undefined as a parameter. The includes method will return true if the array contains an empty element or an element that has the value of undefined .

How check array is empty or not in JavaScript?

The array can be checked if it is empty by using the array. length property. By checking if the property exists, it can make sure that it is an array, and by checking if the length returned is greater than 0, it can be made sure that the array is not empty.


1 Answers

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.

like image 114
Nick Craver Avatar answered Sep 18 '22 17:09

Nick Craver