Remove null values from javascript array

2019-03-14 20:25发布

I am having a javascript array.

addresses = new Array(document.client.cli_Build.value, 
    document.client.cli_Address.value, 
    document.client.cli_City.value, 
    document.client.cli_State.value, 
    document.client.cli_Postcode.value, 
    document.client.cli_Country.value);
document.client.cli_PostalAddress.value = addresses.join(", ");

I have to copy the content of all these array value to the postal address textarea. when i use the above join function, comma has been added for null values. How to remove this extra commas?

Thanks

9条回答
smile是对你的礼貌
2楼-- · 2019-03-14 20:48

Another filter alternative

myArray.filter(function(val){if(val)return val}).join(", ")

document.write(['this','','',,,,'is','a',,,'test'].filter(function(val){if(val)return val}).join(", "));

查看更多
Summer. ? 凉城
3楼-- · 2019-03-14 20:50

If you would like to eliminate all the undefined, null, NaN, "", 0, a simple way to do it is to use a combination of filter call back function and boolean function.

var filterArr=arr.filter(function(val){
   return Boolean(val);  
  });

When you pass a value to the boolean function, if the value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.

Here is an example of this usage:

 function bouncer(arr) {

         var filterArr=arr.filter(function(val){
           return Boolean(val);  
          });

      return filterArr;
    }

Here are some tests:

bouncer([1, null, NaN, 2, undefined]);//should return [1, 2]
bouncer([7, "ate", "", false, 9]);// should return [7, "ate", 9]
bouncer(["a", "b", "c"]);// should return ["a", "b", "c"]
bouncer([false, null, 0, NaN, undefined, ""]);//should return []
查看更多
Luminary・发光体
4楼-- · 2019-03-14 20:52

addresses.filter(Boolean).join(", ")

查看更多
来,给爷笑一个
5楼-- · 2019-03-14 20:54

Use the following code to remove the null values only, its short & simple:

addresses = addresses.filter(n => (n===null) ? false : true).join(', ');
document.client.cli_PostalAddress.value = addresses;

If you want to remove null, 0, false & ""(Empty String) like values, then use this:

document.client.cli_PostalAddress.value = addresses.filter(Boolean).join(', ');
查看更多
狗以群分
6楼-- · 2019-03-14 20:56

Use filter method to remove all falsy values:

var list = [null, undefined, 0, 1, 2, '', 'test'];

// ES5:
var result = list.filter(Boolean).join(', ');
console.log(result);

// ES6, saves 3 characters:
var result = list.filter(x => x).join(', ');
console.log(result);

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-03-14 20:58

You can use filter to filter out the null values:

addresses.filter(function(val) { return val !== null; }).join(", ")
查看更多
登录 后发表回答