1

I have an array:

var countryArray = [];

That I'm dynamically inserting values to with click events:

(on click...)

countryArray.push("Australia");

and then finally appending to a div for output:

$('#summary-countries').append(countryArray+'');

So my output could be:

Australia,United Kingdom,Finland,Japan.

Is there any way how I could insert some text so that it would output as the following:

Australia,United Kingdom,Finland **AND** Japan.

Any help would be appreciated!

3 Answers 3

5

Here's one way:

var countries;

if( countryArray.length > 1 ) { 
    var last = countryArray.pop();
    countries = countryArray.join(', ')+' and '+last;
}
else {
    countries = ''+countryArray;
}

$( '#summary-countries' ).append( countries );
Sign up to request clarification or add additional context in comments.

2 Comments

countryArray.join(', ') would be preferable to countryArray+''
@Eric countryArray is guaranteed to have 0 or 1 elements at that point. I suppose countries = countryArray.length ? countryArray[0] : ''; would be more legible.
1

Yes, there is a way. You are relying on the built-in serialization of arrays, when you call .append(reasonsTravelling+'');. This converts reasonsTravelling into a string, which, by default is a comma separated list.

You have to use a for loop instead and go through all the items in the array. Once you find that the iterator is one before the last index, use the "And" instead of ",".

This fiddle should explain my idea: http://jsfiddle.net/v76Bf/

Comments

-1

You can traverse through and array and find the last index and insert the text before the last value.

for (var i=0;i<countryArray.length;i++)
{
if(i==countryArray.length-1)
{
countryArray[i].join(,).push("And");
}
}

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.