1

I have a String array likes

var arr=["1","2",""];
arr.filter(Boolean);
arr.filter(function(e){return e != ""});

And I used one of these methods but that empty string still here. note: I'm using chrome.

4 Answers4

2

var arr=["1","2","", "3"];
//arr.filter(Boolean);
arr = arr.filter(function(num){return num!=""});
console.log(arr);

You have to assign it back to arr.

Wils
  • 1,178
  • 8
  • 24
2

Your code is working, you just need to correct type retunr to return and save modified array to variable

var arr=["1","2",""];
console.log(arr);
arr.filter(Boolean);
arr = arr.filter(function(e){return e != ""});
console.log(arr);
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
  • your code should work as per code snippet i have posted. Did you see any console error? can you reproduce this on code snippet or jsfiddle so that i can take a look at it – Bhushan Kawadkar Oct 17 '19 at 10:07
1

You have a typo (as @RoryMcCrossan sad), so the code must be:

var arr=["1","2",""];
var newArr = arr.filter(element => element !== "");

console.log(newArr);
Simone Boccato
  • 199
  • 1
  • 14
0

you can use arr.filter to filter a value. but if you are using IE then may be filter is not workng then you need to use pure javascript.

var arr=["1","2",""];
arr=arr.filter(function(o){ return o!=""});
console.log(arr);

output
(2) ["1", "2"]

var k=[];
for(var i=0;i<arr.length;i++){ if(arr[i]!=""){k.push(arr[i])}}
console.log(k);
Negi Rox
  • 3,828
  • 1
  • 11
  • 18