How to sort an array in JavaScript?
javascript
arrays
sorting
25
I have an array of numbers and I want to sort them in ascending order. What is the best way to do this in JavaScript? Are there any pitfalls to watch out for?
2 Answers
15
To sort an array in JavaScript, you can use the `sort()` method. For custom sorting, provide a compare function.
answered 2h ago
8
Remember that `sort()` sorts elements as strings by default if no compare function is provided. For numbers, this can lead to unexpected results like `[1, 10, 2]` instead of `[1, 2, 10]`. Always use a compare function for numeric sorts: `(a, b) => a - b`.
answered 1h ago