简体   繁体   中英

Removing array items with no value with javascript

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM