DEV Community

Nirmal Patel
Nirmal Patel

Posted on

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'
}

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

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

Discussion (0)