00 Votes

JavaScript: Sort Array

Question by Compi | 2015-08-12 at 16:56

Does JavaScript provide any function for sorting and arbitrary array containing some elements?

I have looked up this problem in one of my old books about JavaScript, but the code examples from this book seem to be unnecessary inconvenient. Isn't there any simple function for such an easy task out there?

ReplyPositiveNegative
0Best Answer0 Votes

In JavaScript, an array is providing the method .sort() with which you can easily order the elements of your array. Here is a small example:

var arr = ['E' ,'A', 'D', 'C', 'B'];
arr.sort();
alert(arr);  // A,B,C,D

First, we are creating an array containing some unsorted characters. Then, we are executing the function .sort() and we get a sorted array.

Be careful: This simple method does not sort alphanumerical. This means that the elements 1, 2 and 10 would be arranged to the order 1, 10 and 2, because 10 is starting with 1 and 1 comes before 2. If this could be a problem in your application, your should have looked at the tutorial about sorting the numerical arrays in JavaScript.
2015-08-12 at 20:12

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.