38

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 Answers 9

54

You can use filter to filter out the null values:

addresses.filter(function(val) { return val !== null; }).join(", ")
Sign up to request clarification or add additional context in comments.

16 Comments

Like this better than post processing the joined array elements.
is there a filter in every javascript? I think there is not in some IE
@Victor: See my previous comment.
@chrismarx What I meant it that [null,undefined,"",0,NaN].filter(function(val) { return val; }) returns an empty array and not just [undefined,"",0,NaN]. However, function(val) { return val !== null; } does exactly that.
A better version: addresses.filter(val => { return !!val }).join(', ')
|
13

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

3 Comments

filter(Boolean) removes all the falsy values, so if you want to keep 0 you have to pass it as '0'.
I actually prefer the ES5 version because its clearer what your intention is - I only knew about the ES6 version, so thanks for teaching me the old skool ways :)
I think the ES5 version is obtuse and not clear at all. I would read it as "filter booleans" - I actually have to think, "Oh, Boolean is a constructor that takes an initial value as a parameter, so this is passing the array values into that constructor". I find myself hoping that the constructor doesn't take any more parameters. It doesn't read well at all, imo.
6

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

Comments

5

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

1 Comment

_.compact() performs a filter that removes falsy values: documentcloud.github.com/underscore/#compact
1

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

Comments

0
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 Comments

add a "g" to do multiple search and replace.
this code works like a charm .Thanks for quick reply. document.client.cli_PostalAddress.value=document.client.cli_PostalAddress.value.replace(/(, )+/g,", "); But i am getting a comma added at the end of the address
/*Remove null values*/ document.client.cli_PostalAddress.value=document.client.cli_PostalAddress.value.replace(/(, )+/g,", "); /* Remove last comma */ document.client.cli_PostalAddress.value = document.client.cli_PostalAddress.value.slice(0, -2); /*Remove first comma*/ document.client.cli_PostalAddress.value = document.client.cli_PostalAddress.value.substr(1); I used these codes and working fine now. thank u so much for ur help
0

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.

Comments

0

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

Comments

0

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(', ');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.