Sort Array Without Displaying Commas
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 c
Solution 1:
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
Solution 2:
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(''));
Solution 3:
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/>");
}
Post a Comment for "Sort Array Without Displaying Commas"