0

I'm the perfect case of the "most computer savvy guy gets the task." On the website I'm making, I need to sort a large number of names. The names change often, and lots of people change them. The number of names also change, so indexing by number would also not be a good thing.

My sample code I found looks like this:

<script type="text/javascript">
var fruits = ["Banana<br />", "Orange<br />", "Apple<br />", "Mango<br />",];
document.write(fruits.sort());
</script>

This works with the exception that the commas are displayed on the website. This isn't acceptable. I'm looking for a way to make the commas go away from the website when it's displayed.

0

3 Answers 3

5

An array isn't a string, and the default way of converting it is to join the elements by ,. Just specify your own joining string instead:

var fruits = ["Banana<br />", "Orange<br />", "Apple<br />", "Mango<br />",];
document.write(fruits.sort().join('')); // Don't join by anything
Sign up to request clarification or add additional context in comments.

Comments

0

The sort method returns the sorted array. You could apply it the join method to concatenate all elements of this array using a separator before outputting it:

document.write(fruits.sort().join(''));​

Comments

0

In this case the commas are being displayed because you are writing an collection to the document and hence a separator is being displayed. To avoid this write out the entries manually

for (var i = 0; i < fruits.length; i++) {
  document.write(fruits[i]);
}

Note: It's generally better practice to separate data from display. In this case you mixed the data (fruit name) with the display information (<br/>). Another way to consider writing this is the following

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
for (var i = 0; i < fruits.length; i++) {
  document.write(fruits[i]);
  document.write("<br/>");
}

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.