Sorting list in javascript

How TO — Sort a List

Sorting Ascending and Descending

The first time you click the button, the sorting direction is ascending (A to Z).

Click again, and the sorting direction will be descending (Z to A):

Example

Источник

JavaScript Array sort()

The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.

See Also:

Sort Compare Function

Sorting alphabetically works well for strings («Apple» comes before «Banana»). But, sorting numbers can produce incorrect results. «25» is bigger than «100», because «2» is bigger than «1». You can fix this by providing a «compare function» (See examples below).

Syntax

Parameters

When sort() compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

The sort function will sort 40 as a value lower than 100.

When comparing 40 and 100, sort() calls the function(40,100).

The function calculates 40-100, and returns -60 (a negative value).

Return Value

More Examples

Sort numbers in ascending order:

Sort numbers in descending order:

const points = [40, 100, 1, 5, 25, 10];

// Sort the numbers in ascending order
points.sort(function(a, b));

const points = [40, 100, 1, 5, 25, 10];

// Sort the numbers in descending order:
points.sort(function(a, b));

const points = [40, 100, 1, 5, 25, 10];

// Sort the numbers in ascending order:
points.sort(function(a, b));

let highest = points[points.length-1];

Browser Support

sort() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Источник

Читайте также:  Первая строка html кода
Оцените статью