Home > Web Front-end > JS Tutorial > body text

Array reordering method in JS

高洛峰
Release: 2016-12-07 10:34:55
Original
1364 people have browsed it

1. There are already two methods in the array that can be used directly to reorder: reverse() and sort(). The return value of the

reverse() and sort() methods is the sorted array. The reverse() method will reverse the order of the array items:

var values=[1,2,3,4,5];
values.reverse();
alert(values); //5,4,3,2,1
Copy after login

By default, the sort() method sorts the array in ascending order, and the sort() method will call the toString() transformation method of each array item, Then compare the strings to determine how to sort them. Even though each item in the array is a numeric value, the sort() method compares strings:

var values = [0,1,5,10,15];
values.sort();
alert(values); //0,1,10,15,5
Copy after login

Therefore, the sort() method can receive a comparison function as a parameter.

function compare(value1,value2){
if (value1 < value2){
return -1;
}else if (value1 > value2){
return 1;
}else{
return 0;
}
}
Copy after login

This comparison function can be applied to most data types, just pass it as a parameter to the sort() method:

var values = [0,1,3,7,9,15];
values.sort(compare);
alert(values); //0,1,3,7,9,15
Copy after login

Descending sort can also be produced through the comparison function, just Just exchange the return value of the function:

function compare (value1, value2){
if (value1<value2){
return 1;
}else if {
return -1;
}else{
return 0;
}
}
Copy after login

The sorting conditions of the sort() function are:

parameter is greater than 0, two adjacent elements of arr exchange positions;

parameter is less than 0, two adjacent elements of arr The elements do not exchange positions; the

parameter is equal to 0, and the two adjacent elements of arr are equal in size; so the compare custom function must return a numerical value.

2. For numerical types or the valueOf() method will return the object type of numerical type.


A simpler comparison function can be used. This function only needs the second value minus the first value.

function compare (value1,value2){
return value2 - value1;
}
Copy after login

Related labels:
js
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template