Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use sort function in js

Shulou Source: shulou.com Published: 2022-06-03 09:29:01 09月21日 Update

This article mainly introduces how to use the sort function in js. It is very detailed and has a certain reference value. Friends who are interested must finish it!

The sort method in js is used to sort the elements of the array and return the array. The default sort order is based on the string Unicode code point.

Syntax of sort function

ArrayObject.sort (sortby)

Parameter sortby: optional. Used to specify the sort order, it must be a function.

Note: if you call this method without arguments, the elements in the array are sorted alphabetically or, more precisely, in character encoding order. To achieve this, you should first convert the elements of the array to strings (if necessary) for comparison.

The sort function is sorted alphabetically by default

Vararr1= ['axiajiajiaozhuo']

Arr.sort (); / / ['axiomagy,' baccalaureate, 'cricket,']

Vararr2= [10,5,40,25,100,1]

Arr2.sort (); / / [1, 10, 10, 100, 25, 40, 5] this ranking does not seem to get the desired results.

If you want to get the results you want, whether ascending or descending, you need to provide a comparison function. This function compares the size of the two values and then returns a number that describes the relative order of the two values.

The comparison function should have two parameters an and b, and the return values are as follows:

If an is less than b, that is, a murb is less than zero, a value less than zero is returned, and the array is arranged in ascending order.

If an equals b, 0 is returned.

If an is greater than b, that is, a murb is greater than zero, a value greater than zero is returned, and the array is arranged in descending order.

Sort by numeric size-ascending order

Arr.sort (function (a) b) {

Returna-b

})

Sort by numerical value-descending

Arr.sort (function (a) b) {

Returnb-a

})

Sort by a property value of an object in the array

Vararr= [

{name:'zopp',age:0}

{name:'gpp',age:18}

{name:'yjj',age:8}

]

Functioncompare (property) {

Returnfunction (a _ r _ b) {

Varvalue1=a [property]

Varvalue2=b [property]

Returnvalue1-value2

}

}

Console.log (arr.sort (compare ('age')

Put the array out of order

Arr.sort (function (a) b) {

ReturnMath.random ()-0.5

})

The above is all the contents of the article "how to use the sort function in js". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Sort function array order two elements ascending order parameters size characters content letters strings numeric values methods articles results precision necessity value Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Technology OPPO Reno Shulou Tech Info NVidia