Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove an empty string from array of strings - JQuery

Tags:

arrays

jquery

I have an array ["Lorem", "", "ipsum"]. I would like to remove the empty string from this array and get ["Lorem", "ipsum"].

Is there any way to do this without using the loop and traversing through each element and removing it?

like image 326
Sadiksha Gautam Avatar asked Jan 22 '13 07:01

Sadiksha Gautam


People also ask

How do you remove Blank strings from an array?

To remove the empty strings from an array, we can use the filter() method in JavaScript. In the above code, we have passed the callback function e => e to the filter method, so that it only keeps the elements which return true . empty "" string is falsy value, so it removes from the array.

How do you remove Blank strings from a list in Python?

Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this task. remove() generally removes the first occurrence of an empty string and we keep iterating this process until no empty string is found in list.


2 Answers

You may use filter :

var newArray = oldArray.filter(function(v){return v!==''}); 

The MDN has a workaround for IE8 compatibility. You might also use a good old loop if you're not going to use filter anywhere else, there's no problem with looping...

like image 69
Denys Séguret Avatar answered Oct 09 '22 16:10

Denys Séguret


If you use Javascript 1.6 (probably wont work on IE8 or less) you can use

arr.filter(Boolean) //filters all non-true values 

eg.

console.log([0, 1, false, "", undefined, null, "Lorem"].filter(Boolean)); // [1, "Lorem"]
like image 39
venimus Avatar answered Oct 09 '22 17:10

venimus