Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array in JavaScript

I am not using an associative array. I'm using 1d array like this,

array("1,a","5,b","2,c","8,d","6,f");

How can I sort this array?

The result should be,

array("1,a","2,c","5,b","6,f","8,d");
like image 731
Anish Avatar asked Dec 28 '11 05:12

Anish


2 Answers

sort() without a custom sorting function will sort it how you wish (lexicographically).

>>> ["1,a","5,b","2,c","8,d","6,f"].sort();
["1,a", "2,c", "5,b", "6,f", "8,d"]

Note that this will sort the original array. You can make a shallow copy with slice().

If any of your numbers are larger than 9, and you want to sort it via the ordinal of the number, you will need a custom sorting function.

["1,a","5,b","2,c","8,d","6,f"].sort(function(a, b) {
    return parseInt(a, 10) - parseInt(b, 10);
});
like image 162
alex Avatar answered Oct 28 '22 10:10

alex


Use array.sort() built-in JS function. Documentation here: http://www.w3schools.com/jsref/jsref_sort.asp

like image 26
techfoobar Avatar answered Oct 28 '22 08:10

techfoobar