Home Web Front-end JS Tutorial Sorting of Javascript arrays sort() method and reverse() method_javascript skills

Sorting of Javascript arrays sort() method and reverse() method_javascript skills

May 16, 2016 pm 05:52 PM
sort Array sort

Among them:

1. If no comparison function is specified in JavaScript's sort(), it will be sorted in ascending order by character encoding order by default. That is to say, if we want to sort the values, we may not get the results we want.

2.Javascript's reverse() reverses the order of the elements in the array.

Look at the first point above. If there is an array arr=[1,6,3,7,9], after using arr.sort(), the order of the array is 1,3,6 ,7,9, we got the results we wanted.

Look at the following array sorting: arr=[3,1,16,34,30], if we execute arr.sort(), will we still get the 1,3 we want? What about 16, 30, 34?

After execution, we found that the results are: 1,16,3,30,34. Obviously the results are not what we want. In fact, the sort method sorts the above values ​​in string format, which is consistent with the sorting result of the array arr1=['3','1','16','34','30'].

The code is as follows:

Copy code The code is as follows:

var arr= [3,1,16,34,30];
var arr1=['3','1','16','34','30'];
alert(arr.sort() ); // 1,16,3,30,34
alert(arr1.sort()); // 1,16,3,30,34


Then if We want to get the correct results: 1,3,16,30,34. How should we do it?

Check the javascript manual. The instructions in the manual are as follows:

Definition and usage

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

Syntax

arrayObject.sort(sortby) Parameter Description
sortby Optional. Specifies the sort order. Must be a function.

Return value

A reference to the array. Please note that the array is sorted on the original array and no copy is made.

Explanation

If no parameters are used when calling this method, the elements in the array will be sorted alphabetically, or to be more precise, in the order of character encoding. To achieve this, first convert the array elements 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 describing 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.
=====================================

From the above explanation we It can be understood that if you want to sort by numerical values, then you must provide a comparison function. Common comparison functions are as follows:
Copy code The code is as follows:

function sortArr(m, n){
if(mreturn -1;//less than, return -1
else if(m>n)
return 1;//greater than, return 1
else return 0;//Equal, return 0
}

After being simplified, it can be written in the following two forms:
Copy code The code is as follows:

function sortArr(m,n){
return m-n;
}

Copy code The code is as follows:

function sortArr(m,n){
return m>n?1 :(m}

Then execute arr.sort(sortArr) and find that we can get the results we want: 1,3,16,30 ,34. In other words, the array is sorted in ascending order according to integer values.
In this case, a new question arises. What if we want to sort the array in descending order?

One idea is to change the return value of the sortArr function. If mn, it returns a negative value, and if m=n, it returns 0. That's it.

You can write two functions, one for ascending order and one for descending order. Then just call different functions according to different needs.

In addition, we can also call another function reverse() mentioned above to achieve it easily. When we sort the array in ascending order, then the array calls the reverse() method to reverse the order of the array, so that the array can be implemented Sorted in descending order.

The code is as follows:
Copy code The code is as follows:

arr.sort (sortArr).reverse();

Summary: This article mainly introduces the sorting of arrays in Javascript. Since the default is to sort by strings, to achieve sorting according to other forms of rules, you must define your own comparison function. .
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 AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

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)

Explore the underlying principles and algorithm selection of the C++sort function Explore the underlying principles and algorithm selection of the C++sort function Apr 02, 2024 pm 05:36 PM

The bottom layer of the C++sort function uses merge sort, its complexity is O(nlogn), and provides different sorting algorithm choices, including quick sort, heap sort and stable sort.

How to implement drag-and-drop sorting and drag-and-drop operations in uniapp How to implement drag-and-drop sorting and drag-and-drop operations in uniapp Oct 19, 2023 am 09:39 AM

Uniapp is a cross-platform development framework. Its powerful cross-end capabilities allow developers to develop various applications quickly and easily. It is also very simple to implement drag-and-drop sorting and drag-and-drop operations in Uniapp, and it can support drag-and-drop operations of a variety of components and elements. This article will introduce how to use Uniapp to implement drag-and-drop sorting and drag-and-drop operations, and provide specific code examples. The drag-and-drop sorting function is very common in many applications. For example, it can be used to implement drag-and-drop sorting of lists, drag-and-drop sorting of icons, etc. Below we list

Fast array sorting method that preserves key names in PHP Fast array sorting method that preserves key names in PHP May 02, 2024 pm 03:06 PM

Fast array sorting method in PHP that preserves key names: Use the ksort() function to sort the keys. Use the uasort() function to sort using a user-defined comparison function. Practical case: To sort an array of user IDs and scores by score while retaining the user ID, you can use the uasort() function and a custom comparison function.

JS array sorting: in-depth analysis of the working principle and mechanism of the sort() method JS array sorting: in-depth analysis of the working principle and mechanism of the sort() method Dec 28, 2023 am 11:47 AM

To deeply understand JS array sorting: the principles and mechanisms of the sort() method, specific code examples are required. Introduction: Array sorting is one of the very common operations in our daily front-end development work. The array sorting method sort() in JavaScript is one of the most commonly used array sorting methods. However, do you really understand the principles and mechanisms of the sort() method? This article will give you an in-depth understanding of the principles and mechanisms of JS array sorting, and provide specific code examples. 1. Basic usage of sort() method

Sort array using Array.Sort function in C# Sort array using Array.Sort function in C# Nov 18, 2023 am 10:37 AM

Title: Example of using the Array.Sort function to sort an array in C# Text: In C#, array is a commonly used data structure, and it is often necessary to sort the array. C# provides the Array class, which has the Sort method to conveniently sort arrays. This article will demonstrate how to use the Array.Sort function in C# to sort an array and provide specific code examples. First, we need to understand the basic usage of the Array.Sort function. Array.So

How to keep key names after sorting PHP array by value? How to keep key names after sorting PHP array by value? May 02, 2024 pm 04:09 PM

The way to sort an array by value in PHP while preserving the key names is to use the usort() function to sort the array by value. Pass an anonymous function to the usort() function as a comparison function, which returns the difference in element values. usort() will sort the array according to the anonymous function while keeping the key names unchanged.

Guide to writing a custom sorting algorithm for PHP arrays Guide to writing a custom sorting algorithm for PHP arrays Apr 27, 2024 pm 06:12 PM

How to write a custom PHP array sorting algorithm? Bubble sort: Sorts an array by comparing and exchanging adjacent elements. Selection sort: Select the smallest or largest element each time and swap it with the current position. Insertion sort: Insert elements one by one into the sorted part.

Sort arrays according to custom sorting rules in PHP, retaining original key names Sort arrays according to custom sorting rules in PHP, retaining original key names May 04, 2024 am 09:27 AM

In PHP, use the uasort() function to sort an array according to custom sorting rules while retaining the original key names. A custom comparison function is a function that takes two elements as input and returns an integer: a negative number means the former is less than the latter, zero means they are equal, and a positive number means the former is greater than the latter.

See all articles