Reputation: 3765
I have [Address]
, [City]
, [State]
, [Zip]
in an array, but any one or more of these may be empty.
I would like to display them on the page with a comma between each key-value pair, but if both State and ZIP are present, they should not get a comma in between!
This is what I have so far:
var student_address_array = [Address, City, State, Zip]; //Put variables into array
var student_address_array_cleaned = student_address_array.filter(function(v){return v!==''}); //Remove empty array items
var student_address = student_address_array_cleaned.join(', '); // Convert array to string with ', ' as the delimiter
But this puts a comma before ZIP code...
Is the only answer RegEx of some sort?
Upvotes: 1
Views: 208
Reputation: 337626
Concatenate State
and Zip
in to the same element of the array and then join the array by comma:
var student_address_array = [student_info.Address1, student_info.City, (student_info.State + ' ' + student_info.Zip).trim()];
var student_address = student_address_array.join(', ');
var student_info = {
Address1: 'address1',
City: 'city',
State: 'CA',
Zip: '90210'
};
var student_address_array = [student_info.Address1, student_info.City, (student_info.State + ' ' + student_info.Zip).trim()];
var student_address = student_address_array.join(', ');
console.log(student_address);
Upvotes: 2