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条回答
做自己的国王
2楼-- · 2019-03-14 21:00
document.client.cli_PostalAddress.value = 
    document.client.cli_PostalAddress.value.replace(/(, )+/g,", ");

Or should it be

document.client.cli_PostalAddress.value = 
    document.client.cli_PostalAddress.value
    .replace(/(null, )/g,"").replace(/(, null)/g,"");

??

查看更多
疯言疯语
3楼-- · 2019-03-14 21:03

One could also use Array.prototype.reduce().

It reduces an array to a single value, e.g. a string. Like so:

addresses.reduce(function (a, b) {
        if (a && b) { return a + ', ' + b; }
        if (a) { return a; }
        return b;
      }, '');

a holds the intermediate result, b holds the current element.

查看更多
淡お忘
4楼-- · 2019-03-14 21:04

Underscore is a nice utility library for functional programming and list manipulation:

_.filter(addresses, function(val) { return val !== null; }).join(", ");

Edit: And there is a more compact way (Thanks Andrew De Andrade!):

_.compact(addresses).join(", ");
查看更多
登录 后发表回答