Loading Please Wait...
JavaScript array sorting arrange the array elements in ascending or descending order.
The sort() method sorts an array alphabetically
const services = ["Website", "Applications", "Software"];
services.sort(); // ["Applications", "Software", "Website"]
The reverse() method reverses the elements in an array. You can use it to sort an array in descending order.
const services1 = ["Website", "Applications", "Software"];
services1.reverse(); // ["Software", "Applications", "Website"]
// reverse sorting
const services2 = ["Website", "Applications", "Software"];
services2.sort(); // ["Applications", "Software", "Website"]
services2.reverse(); // ["Website", "Software", "Applications"]
By default, the sort() function sorts values as strings.
This works well for strings ("Applications" comes before "Software").
However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce incorrect result when sorting numbers. You can fix this by providing a compare function.
// ascending order
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// descending order
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(){return 0.5 - Math.random()});
The above example, array.sort(), is not accurate. It will favor some numbers over the others. The most popular correct method, is called the Fisher Yates shuffle, and was introduced in data science as early as 1938.
const points = [40, 100, 1, 5, 25, 10];
for (let i = points.length -1; i > 0; i--) {
let j = Math.floor(Math.random() * (i+1));
let k = points[i];
points[i] = points[j];
points[j] = k;
}
There are no built-in functions for finding the max or min value in an array. However, after you have sorted an array, you can use the index to obtain the highest and lowest values.
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
points[0]; // min value
points[points.length - 1]; // max value
You can use Math.max.apply to find the highest number in an array.
You can use Math.min.apply to find the lowest number in an array.
const points = [40, 100, 1, 5, 25, 10];
let max = Math.max.apply(null, points); // 100
let min = Math.min.apply(null, points); // 1
How you feel about this blog:
Share this blog on:
If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com
Contact UsWe are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..
Copyright ©
, Lynxsia IT Solutions, All rights reserved