Home Web Front-end JS Tutorial Detailed explanation of the use of sort() method in javascript_javascript skills

Detailed explanation of the use of sort() method in javascript_javascript skills

May 16, 2016 pm 03:41 PM
javascript sort() method

Syntax: arrayObject.sort(sortby); the parameter sortby is optional. Specifies the sort order. Must be a function.

The sort() method is used to sort the elements of the array.

If this method is called without parameters, the elements in the array will be sorted alphabetically, or more precisely, in character encoding order. To achieve this,

First convert the elements of the array into strings (if necessary) for comparison.

If you want to sort by other criteria, you need to provide a comparison function, which compares two values ​​and returns a number that describes the relative order of the two values.

The comparison function should have two parameters a and b, and its return value is as follows:

If a is less than b, a should appear before b in the sorted array, then return a value less than 0.

If a is equal to b, return 0.

If a is greater than b, return a value greater than 0.

Use the sort() method in js to sort numbers

1

2

3

4

<script>

  var arr = [23,12,1,34,116,8,18,37,56,50];

  alert(arr.sort();

</script>

Copy after login

Return: [1, 116, 12, 18, 23, 34, 37, 50, 56, 8]

The above code does not sort the numbers according to their size. To achieve this, a sorting function must be used:

1

2

3

4

5

6

7

8

9

10

11

12

13

<script>

  var arr = [23,12,1,34,116,8,18,37,56,50];

  function sequence(a,b){

    if (a>b) {

      return 1;

    }else if(a<b){

      return -1

    }else{

      return 0;

    }

  }

  console.log(arr.sort(sequence));

</script>

Copy after login

Return: [1, 8, 12, 18, 23, 34, 37, 50, 56, 116] (no problem)

Of course, you can also write the sorting function into the sort() method:

1

2

3

4

5

6

7

8

9

10

11

12

13

<script>

  var arr = [23,12,1,34,116,8,18,37,56,50];

  var arr2 = arr.sort(function(a,b){

     if (a>b) {

      return 1;

    }else if(a<b){

      return -1

    }else{

      return 0;

    

  })

  console.log(arr2);

</script>

Copy after login

Return: [1, 8, 12, 18, 23, 34, 37, 50, 56, 116] (no problem either)

can also be simplified to this way of writing
Because: if a is less than b, a should appear before b in the sorted array, then a value less than 0 is returned.

If a is equal to b, return 0.

If a is greater than b, return a value greater than 0

1

2

3

4

5

6

7

<script>

  var arr = [23,12,1,34,116,8,18,37,56,50];

  function sequence(a,b){

    return a - b;

  }

  console.log(arr.sort(sequence));

</script>

Copy after login

Returns: [1, 8, 12, 18, 23, 34, 37, 50, 56, 116] (also correct)

Sorting in alphabetical order is much simpler, just use the sort() method directly:

1

2

3

4

<script>

  var arr = ['fanda','banner','find','zoom','index','width','javascript'];

  console.log(arr.sort());

</script>

Copy after login

Return: ["banner", "fanda", "find", "index", "javascript", "width", "zoom"]

Now when I am learning javascript, I found that the sort() function is a bit strange (maybe it is a problem with my level -_-!), so I will record what I found here. The parameters of the sort() method are very strange. They must be functions, but they are also optional parameters. If there are no parameters, they will be arranged in dictionary order of strings by default (even numerical values ​​will be converted into strings for processing. ). This parameter is to be able to compare the size of two values, such as:

Copy code The code is as follows:

function sortNumber(a, b){
return a - b; //What is returned here is their difference. If it is less than 0, a will be ranked in front. If it is greater than 0, b will be ranked in front. If it is 0, it will be whatever. . (Bubble sorting method!!)
}

The application is as follows (this example is so classic!!):

1

2

3

4

5

6

7

8

9

<script type="text/javascript">

function sortNumber(a,b){return a - b}

var arr = new Array(3)

arr[0] = "10";

arr[1] = "5";

arr[2] = "4";

document.write(arr + "<br />");

document.write(arr.sort(sortNumber));

</script>

Copy after login

Then the original arrangement of 10,5,4 will become 4,5,10. Here is an explanation of this process. Obviously sortNumber should have two parameters, but when we call it, there is no parameter at all. Why? Compare? This is like this. When arr calls sort starting from the first number, there is no number before 10 to compare with it, so it goes to the second number, which is 5. At this time, 10 will be compared with 5, so it will be called sortNumber and pass 10 and 5 in, this is the nature of sort().

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to implement an online speech recognition system using WebSocket and JavaScript

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to implement an online reservation system using WebSocket and JavaScript

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

How to use JavaScript and WebSocket to implement a real-time online ordering system

Optimizing JS array sorting: performance exploration using the sort() method Optimizing JS array sorting: performance exploration using the sort() method Dec 28, 2023 pm 03:52 PM

Optimizing JS array sorting: performance exploration using the sort() method

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecasting system

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

Simple JavaScript Tutorial: How to Get HTTP Status Code

Custom sorting: Implementation method of sorting using JS array sort() method Custom sorting: Implementation method of sorting using JS array sort() method Dec 28, 2023 am 10:59 AM

Custom sorting: Implementation method of sorting using JS array sort() method

See all articles