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.

7
  • 3
    Typo. retunr -> return Commented Oct 17, 2019 at 9:57
  • 3
    Also note that the filter() method returns a new array, it doesn't work on the existing one by reference. As such you need to use arr = arr.filter(... Commented Oct 17, 2019 at 9:58
  • sorry but i type return it still not working Commented Oct 17, 2019 at 9:58
  • No, i used one of them, still not working Commented Oct 17, 2019 at 10:03
  • 5
    This works absolutely fine, as you can see in the snippet in @BhushanKawadkar's answer. If it's not working for you then there must be another underlying problem. Please check the console for errors, and post a more complete example of your code. Commented Oct 17, 2019 at 10:07

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

1 Comment

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
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);

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.