Array.sort([sorter]) Last updated: 14. Sep 2023

Sorts the specified array (modifying the array that the sort method is called from).

Parameters

Name Type Description
sorter (optional) function Evaluating function to use to sort items by.

Returns

The same array after sorting has executed. The array that is called from is modified.

Example

Code example (JS)

JS is normal JavaScript either running in the browser or on the Docly™ server.
// Sorting values
var array1 = ["e", "d", "c", "a", "b"];
array1.sort();
write(JSON.stringify(array1));

// Sorting objects
var items = [
  { name: 'Edward', value: 12 },
  { name: 'The', value: -2 },
  { name: 'Xyz', value: 27 }
];
items.sort((a, b) => a.value - b.value);
write("\n\nSorted by value (number):\n");
write(JSON.stringify(items));

// Sorting by string
items.sort((a, b) => a.name.localeCompare(b.name));
write("\n\nSorted by name (string):\n");
write(JSON.stringify(items));

Output

The JS code above produces the output shown below:
["a","b","c","d","e"]

Sorted by value (number):
[{"name":"The","value":-2},{"name":"Edward","value":12},{"name":"Xyz","value":27}]

Sorted by name (string):
[{"name":"Edward","value":12},{"name":"The","value":-2},{"name":"Xyz","value":27}]