Joining multiple Strings into one comma-separated String

nirmaljpatel

Nirmal Patel

Posted on July 22, 2020

Joining multiple Strings into one comma-separated String

One of the mobile apps I work on displays the user's address.

The API returns the address split across multiple fields in the following format:

let address = {
    addressLine1: 'xxx',
    addressLine2: 'yyy',
    city: 'zzz',
    state: 'AA',
    zipcode: 'ddddd'
}
Enter fullscreen mode Exit fullscreen mode

The caveat here is that one or more fields could be null/blank depending on what data was entered by the user at time of creating the address.

However, when displaying on the screen we want to ignore any blanks and show a consistent comma-separated string.

let array = [
    address.addressLine1,
    address.addressLine2,
    address.city,
    address.state,
    address.zipcode
];

return array.filter(function(val) {
    return val;
}).join(', ');
Enter fullscreen mode Exit fullscreen mode

.filter() removes any falsy strings - both blanks, nulls.
.join() takes care of adding a , only when needed to join multiple strings.

💖 💪 🙅 🚩
nirmaljpatel
Nirmal Patel

Posted on July 22, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related