Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty strings from array while keeping record Without Loop?

This question was asked here: Remove empty strings from array while keeping record of indexes with non empty strings

If you'd notice the given as @Baz layed it out;

"I", "am", "", "still", "here", "", "man" 

"and from this I wish to produce the following two arrays:"

"I", "am", "still", "here", "man" 

All the Answers to this question referred to a form of looping.

My question: Is there a possibility to remove all indexes with empty string without any looping? ... is there any other alternative apart from iterating the array?

May be some regex or some jQuery that we are not aware of?

All answers or suggestions are highly appreciated.

like image 428
Universal Grasp Avatar asked Nov 10 '13 10:11

Universal Grasp


People also ask

How would you eliminate empty 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 clear an empty array?

Answer: Use the PHP array_filter() function You can simply use the PHP array_filter() function to remove or filter empty values from an array. This function typically filters the values of an array using a callback function.

Can you leave an array empty?

1) Assigning it to a new empty array This is the fastest way to empty an array: a = []; This code assigned the array a to a new empty array. It works perfectly if you do not have any references to the original array.


1 Answers

var arr = ["I", "am", "", "still", "here", "", "man"] // arr = ["I", "am", "", "still", "here", "", "man"] arr = arr.filter(Boolean) // arr = ["I", "am", "still", "here", "man"] 

filter documentation


// arr = ["I", "am", "", "still", "here", "", "man"] arr = arr.filter(v=>v!=''); // arr = ["I", "am", "still", "here", "man"] 

Arrow functions documentation

like image 172
Isaac Avatar answered Oct 13 '22 17:10

Isaac