Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 903
Krishna Priya Avatar asked Jan 25 '10 11:01

Krishna Priya


People also ask

How do you remove null values from an array?

To remove all null values from an array:Declare a results variable and set it to an empty array. Use the forEach() method to iterate over the array. Check if each element is not equal to null . If the condition is satisfied, push the element into the results array.

How do you filter an undefined array?

To remove all undefined values from an array:Use the Array. filter() method to iterate over the array. Check if each value is not equal to undefined and return the result. The filter() method will return a new array that doesn't contain any undefined values.


1 Answers

You can use filter to filter out the null values:

addresses.filter(function(val) { return val !== null; }).join(", ") 
like image 158
Gumbo Avatar answered Sep 29 '22 06:09

Gumbo