How to sort array in javascript
To sort an array in JavaScript, you can use the sort()
method. This method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, but you can specify a different sort order by passing a compare function to the sort()
method.
Here is an example of how you can use the sort()
method to sort an array of numbers in ascending order:
var numbers = [4, 2, 5, 1, 3];
numbers.sort();
console.log(numbers); // [1, 2, 3, 4, 5]
To sort the array in descending order, you can pass a compare function to the sort()
the method that compares the elements in reverse order. Here is an example:
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return b - a;
});
console.log(numbers); // [5, 4, 3, 2, 1]
Keep in mind that the sort()
method modifies the original array, so if you want to preserve the original array, you should make a copy of it before sorting. You can do this using the slice()
method, like this:
var numbers = [4, 2, 5, 1, 3];
var sortedNumbers = numbers.slice().sort();
console.log(numbers); // [4, 2, 5, 1, 3]
console.log(sortedNumbers); // [1, 2, 3, 4, 5]
I hope this helps. Let me know if you have any other questions.
For more interesting posts follow me