What is array sort in javascript?

 Array sort method javascript:

 

sort() method doing to sort alphabetically sequence if array value is a string, string value given first priority to capital letter alphabet in (A-Z) and then move to the small letter as (a-z).

And if the value is as a number format then it sorting with (1-100) according to digit like 1, 10, 11, 4 not according to value increased or decreased if you want to sort with according to value size then use a function as below:

Syntax of sort method:

array.sort()

 

sort example in javascript:

 

const colors = ["Red", "blue", "Black", "Orange", "White"];

colors.sort();

console.log(colors);

// Array ["Black", "Orange", "Red", "White", "blue"]

 

const array1 = [1, 30, 4, 100, 21, 10, 11, 20];

array1.sort();

console.log(array1);

// Array [1, 10, 100, 11, 20, 21, 30, 4]

 

const array2 = [1, 30, 100, 4, 50, 21, 10, 11, 20];

array2.sort(function(a, b){return a-b});

console.log(array2);

// Array [1, 4, 10, 11, 20, 21, 30, 50, 100]



No comments:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.