Reorder an array in Javascript

Description

There are two methods we can use to reorder an array: reverse() and sort().

Both reverse() and sort() return a reference to the array on which they were applied.

reverse()

reverse() method reverses the order of items in an array.


var values = [1, 2, 3, 4, 5];
values.reverse();
console.log(values);       //5,4,3,2,1

The code above generates the following result.

sort()

By default, the sort() method sort items in ascending order.

sort() calls String() on every item and then compares the strings to determine the order, even if all items in an array are numbers.


var values = [0, 1, 5, 10, 15];
values.sort();
console.log(values);    //0,1,10,15,5

Even though 5 is less than 10, the string "10" comes before "5".

The code above generates the following result.

Comparison function

sort() method can have in a comparison function to indicate the sequence.

A comparison function accepts two arguments and returns

  • a negative number if the first argument should come before the second,
  • a zero if the arguments are equal
  • a positive number if the first argument should come after the second.

Here's an example of a simple comparison function:


function compare(value1, value2) {//from   ww  w . jav a 2 s. c o m
    if (value1 < value2) {
        return -1;
    } else if (value1 > value2) {
        return 1;
    } else {
        return 0;
    }
}
var values = [0, 1, 5, 10, 15];
values.sort(compare);
console.log(values);    //0,1,5,10,15

To sort in descending order, switch the return values like this:


function compare(value1, value2) {/*from  ww  w.j  a  v a2s .  c  o  m*/
    if (value1 < value2) {
        return 1;
    } else if (value1 > value2) {
        return -1;
    } else {
        return 0;
    }
 }

var values = [0, 1, 5, 10, 15];
values.sort(compare);
console.log(values);    //15,10,5,1,0





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions