Array.sort

sort — Sorts an array.

Description

Array.sort([function compare])

Parameters

Name Description Type Default Optional
compare function Yes

Return values

The sorted array.

Examples

Example #1 – sort example
var array = [32, 8, 2, 16, 4]; console.log(array); // [32, 8, 2, 16, 4] console.log(array.sort()); // [16, 2, 32, 4, 8] console.log(array); // [16, 2, 32, 4, 8]
Example #2 – sort example
var array = [32, 8, 2, 16, 4]; var compare = function (a, b) { if (a < b) { return -1; } else if (a > b) { return 1; } return 0; }; console.log(array); // [32, 8, 2, 16, 4] console.log(array.sort(compare)); // [2, 4, 8, 16, 32] console.log(array); // [2, 4, 8, 16, 32]

A shorter inline version.

var array = [32, 8, 2, 16, 4]; console.log(array); // [32, 8, 2, 16, 4] console.log(array.sort(function (a, b) { return a - b; })); // [2, 4, 8, 16, 32] console.log(array); // [2, 4, 8, 16, 32]

External references