Sorting Arrays In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Sorting Arrays In JavaScript.
Sorting Arrays In JavaScript
JavaScript provides several methods to sort arrays, including the sort()
method, which is the simplest way to sort an array. By default, it sorts the elements in ascending order according to their Unicode code points. For example:
Code 1 For .sort() Method In JavaScript
let fruits = ['banana', 'apple', 'kiwi', 'mango'];
fruits.sort();
console.log(fruits);
Output
[‘apple’, ‘banana’, ‘kiwi’, ‘mango’]
If you want to sort the elements in a specific order, you can pass a comparison function as an argument to the sort()
method. The comparison function should return a negative, zero, or positive value, depending on the arguments, like:
Code 2 For .sort() Method In JavaScript
let numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
Output
[1, 2, 3, 4, 5]
Another way to sort arrays in JavaScript is to use the Array.prototype.slice()
method to create a new array and sort it, like this:
Code 3 For slice().sort() Method In JavaScript
let names = ['John', 'Jane', 'Jim', 'Jill'];
let sortedNames = names.slice().sort();
console.log(sortedNames);
Output
['Jane', 'Jim', 'Jill', 'John']
This method creates a shallow copy of the original array and sorts it without affecting the original array.
Conclusion
If you liked this post Sorting Arrays In JavaScript, then please share this with your friends and make sure to bookmark this website for more awesome content.