sort()  Array  instance method JS Home  <<  JS Reference  <<  Array  <<  sort()

Description

Sorts the elements within an array.

Syntax

Signature Description
anArray.sort([sortOrderFunction])Sorts the elements within an array.

Parameters

Parameter Description
sortOrderFunctionSpecifies a function that designates a sort order. If omitted sort will be done in lexographic order.

Examples

The code below creates an array then sorts it without a sort order function.


/*
 Create an array of names.
 Sort elements.
 sortNames = ['Fred', 'Jed', 'Ned', 'Neil', 'Ted'] after sort().
 */
 
var sortNames = ['Fred', 'Ned', 'Ted', 'Jed', 'Neil'];
alert(sortNames);

sortNames.sort();
alert(sortNames);

Press the button below to action the above code:

The code below creates an array then sorts it using a sort order function.


/*
 Create an array of numbers.
 Sort elements using a function.
 sortNumbers = [1, 2, 3, 4, 5] after sort().
 */
 
var sortNumbers = [5, 1, 3, 4, 2];
alert(sortNumbers);

sortNumbers.sort(function(a, b) {  
  return a - b;  
});
alert(sortNumbers);

Press the button below to action the above code:

Related Tutorials

JavaScript Intermediate Tutorials - Lesson 1 - Arrays

JavaScript Basics

JavaScript Basics

JavaScript Intermediate

JavaScript Intermediate

JavaScript Advanced

JavaScript Advanced

JavaScript Reference

JavaScript Entities

Globals

Array

Class Properties
prototype
Instance Properties
constructor
length
Class Methods
None.
Instance Methods Getters
concat()
join()
slice()
toString()
Instance Methods Setters
pop()
push()
reverse()
shift()
sort()
splice()
unshift()

Statements

Operators