3
\$\begingroup\$

Recently I wrote some code to take two arrays of data and create a title. Each array could have 0-n elements. However, the multiple if statements seem messy to me. Is there a nicer way to do this? Perhaps one that harnesses the power of jQuery better?

var campaign_names = data["campaign_names"];
var list_names = data["list_names"];
var title;
if (campaign_names && campaign_names.length > 1) {
 campaign_names = campaign_names.join(", ");
} else if (campaign_names) {
 campaign_names = campaign_names[0];
}
if (list_names && list_names.length > 1) {
 list_names = list_names.join(", ");
} else if (list_names) {
 list_names = list_names[0];
}
if (campaign_names && list_names) {
 title = campaign_names + " & " + list_names;
} else if (campaign_names) {
 title = campaign_names; 
} else if (list_names) {
 title = list_names;
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 18, 2014 at 18:31
\$\endgroup\$
0

2 Answers 2

1
\$\begingroup\$

Fun question,

if (campaign_names && campaign_names.length > 1) {
 campaign_names = campaign_names.join(", ");
} else if (campaign_names) {
 campaign_names = campaign_names[0];
}

is equivalent to

if (campaign_names && campaign_names.length ) {
 campaign_names = campaign_names.join(", ");
}

if you initialized campaign_names and list_names to '' you could simplify the last part to

if (campaign_names && list_names) {
 title = campaign_names + " & " + list_names;
} else {
 title = campaign_names + list_names; 
}

Personally I would go for this:

var campaigns = data["campaign_names"] || [],
 lists = data["list_names"] || [],
 title;
if (campaigns.length) {
 campaigns = campaigns .join(", ");
}
if (lists.length) {
 lists = lists.join(", ");
}
if (campaigns && lists) {
 title = campaigns + " & " + lists;
} else {
 title = campaigns + lists;
}

If I was feeling ternary that day I would write the last part as

 title = campaigns + (campaigns&&lists) ? " & " : "" + lists;
answered Nov 18, 2014 at 18:51
\$\endgroup\$
1
\$\begingroup\$

Leveraging @konjin's code, I might use an array of property names to make it easy to add/remove them without affecting the code.

var propertyList = [ "campaign_names", "list_names" ],
 tempList = [ ],
 tempTitle = '',
 title = '';
for( var i=0; i<propertyNames.length; ++i ) {
 tempList = data[ propertyNames[i] ] || [ ];
 tempTitle = tempList.join(", ");
 title = title + (title && tempTitle) ? " & " : "" + tempTitle;
}
answered Nov 18, 2014 at 21:38
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.