I have a variable that looks like this:
["something here", "", "something else here", ""]
As you can see there are a empty entries.
I need to remove them so that the array contains no empty entries.
How can I do this?
I have a variable that looks like this:
["something here", "", "something else here", ""]
As you can see there are a empty entries.
I need to remove them so that the array contains no empty entries.
How can I do this?
You can use the Array filter method. filter(Boolean)
filters all falsy items.
['',null,0,1].filter(Boolean) // [1]
const arr = ["something here", "", "something else here", ""];
const newArr = arr.filter(Boolean);
console.log(newArr);
You can use filter()
and check length
of string
let arr =["something here", "", "something else here", ""];
console.log(arr.filter(a => a.length))
Use the following code
let array ="something here", "", "something else here", ""];
array.forEach((item,index)=>{
if(item===""){
array.splice(index,1);
}
});
There is a method in JavaScript called filter. This method is responsible to literally filter which values you want (or not).
In this case, maybe you can use the following approach:
var filtered = ["something here", "", "something else here", ""].filter(function(item) {
return item != "";
});
The filtered variable will have the result:
["something here", "something else here"]
One last option, similar to the Boolean one, is a basic filter returning the element if the element is not null, but I personnaly find it more explicit than Boolean:
let array = ['hi', 'this', '', 'is', 'a', '', 'demo']
let filteredArray = array.filter(str => str)
// filteredArray will be equal to ['hi', 'this', 'is', 'a', 'demo']