How to sort an array in javascript?
October 26, 2018
It is very simple to sort in JS. Just use the .sort()
method. But there are a few important things to know and be aware of:
Sorting a-z, just use .sort():
word_array = [
"animal",
"phone",
"water",
"computer",
"bottle",
];
console.log(word_array.sort()); // (5) ["animal", "bottle", "computer", "phone", "water"]
However, if you use .sort() on an array of numbers it will not sort it correctly:
num_array = [
1000,
200,
22,
2,
102,
199,
150,
100000,
2.24,
];
console.log(num_array.sort()); //(9) [1000, 100000, 102, 150, 199, 2, 2.24, 200, 22]
The output from this - [1000, 100000, 102, 150, 199, 2, 2.24, 200, 22]
is clearly not sorted propperly. It sorted it by comparing character by character, as if it was a string comparison.
You can fix this by providing a comparison function to sort, like this:
num_array = [
1000,
200,
22,
2,
102,
199,
150,
100000,
2.24,
];
console.log(num_array.sort(function(a,b) { return a-b; }));
And this will now output the correctly sorted array: [2, 2.24, 22, 102, 150, 199, 200, 1000, 100000]