Skip to content Skip to sidebar Skip to footer

Remove Null Values From Javascript Array

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.cl

Solution 1:

You can use filter to filter out the null values:

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

Solution 2:

Another filter alternative

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

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

Solution 3:

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

Solution 4:

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

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

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

_.compact(addresses).join(", ");

Solution 5:

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

??

Post a Comment for "Remove Null Values From Javascript Array"