JavaScript Array sort
Method (Live Playground)
The JavaScript array sort
method sorts the elements of an array in place and returns the sorted array.
Here's a basic example:
let fruits = ['banana', 'apple', 'cherry'];
fruits.sort();
console.log(fruits);
// Expected output: ['apple', 'banana', 'cherry']
In this example, fruits.sort();
sorts the array fruits
in alphabetical order.
Live Playground, Try it Yourself
For sorting numbers, you need to pass a compare function:
let numbers = [40, 10, 100, 25, 15];
numbers.sort(function (a, b) {
return a - b;
});
console.log(numbers);
// Expected output: [10, 15, 25, 40, 100]
In this case, numbers.sort(function(a, b) { return a - b; });
sorts the numbers in ascending order.
Live Playground, Try it Yourself
And here's how you can sort in descending order:
let numbers = [40, 10, 100, 25, 15];
numbers.sort(function (a, b) {
return b - a;
});
console.log(numbers);
// Expected output: [100, 40, 25, 15, 10]
Live Playground, Try it Yourself
The sort
method modifies the original array. Be aware of this when using it.
Understanding the sort
method is vital as it enables you to order your data in a way that makes it easier to work with.