2

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?

5 Answers5

4

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);
d-h-e
  • 2,478
  • 1
  • 10
  • 18
0

You can use filter() and check length of string

let arr =["something here", "", "something else here", ""];
console.log(arr.filter(a => a.length))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

Use the following code

let array ="something here", "", "something else here", ""];
array.forEach((item,index)=>{
    if(item===""){
        array.splice(index,1);
    }
});
Sathiraumesh
  • 5,949
  • 1
  • 12
  • 11
0

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"]
Camilo Silva
  • 83
  • 1
  • 1
  • 8
0

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']
Tyrannas
  • 4,303
  • 1
  • 11
  • 16