Отсортировать массив по возрастанию javascript. Информатика в JavaScript: Быстрая сортировка (Quicksort)

Приветствую всех, кто заинтересовался такой темой, как JavaScript многомерные массивы и сортировка. В текущей публикации я постараюсь во всех подробностях раскрыть данную тему.

Поэтому после прочтения статьи вы узнаете, зачем в веб-приложениях используются многомерные массивы, как они создаются и каким образом ими можно управлять и сортировать. Давайте приступим к обучению!

Как создаются многомерные массивы и для чего они нужны?

Для начала стоит вспомнить, как создается обычный одномерный массив.

var array =

А теперь запомните, что многомерный массив – это массив массивов. Соглашусь, звучит, как тавтология. Однако прочитайте определение еще раз. Действительно, многомерный массив состоит из определенного количества вложенных в него .

Рассмотрим следующую ситуацию. В начале некой игры пользователь вводит свое имя, а после окончания ему на экран выводится рейтинговая таблица с именами игроков и их рекордами.

Понятное дело, что такая информация хранится в базе данных. Но когда мы ее вытягиваем из БД, то получаем многомерный массив. Ведь в каждом подмассиве хранится логин игрока и количество набранных очков.

Выглядеть все это будет следующим образом:

var results = [ ["Маркус", 333], ["Наташа", 211], ["Алексей", 124] ];

Как видите, информация может храниться разнородная. Это могут быть и строки, и числа, и даже . Такое возможно потому, что массивы в являются нетипизированными.

При этом обращение к элементам происходит через двойной оператор .

Для закрепления материала проанализируйте небольшую программку.

Значение results =

var results = [ ["Маркус", 333], ["Наташа", 211], ["Алексей", 124] ]; document.getElementById("demo").innerHTML = results;

Массивы являются достаточно удобным средством для хранения упорядоченных комплексных данных при их обработке. К тому же работать с ними очень удобно и при этом скорость их обработки достаточно высокая.

Способы сортировки данных

Для массивов в JavaScript-е предусмотрен встроенный метод под названием sort () . Данный инструмент очень гибок. И сейчас объясню почему.

Если вы используете метод без параметров, то он автоматически упорядочивает подмассивы по первому элементу в алфавитном порядке. Так, при вызове results. sort () разбираемый объект будет выглядеть вот так:

Алексей,124

Маркус,333

Наташа,211

А если поменять в каждом вложенном массиве элементы местами, то получится:

124,Алексей

211,Наташа

333,Маркус

При этом для сравнения все элементы временно преобразовываются к строкам.

Если же для решения какой-то конкретной задачи вам необходима функция, сортирующая элементы нестандартным способом, то вы можете написать ее самостоятельно и передать в качестве параметра в sort () . При этом стоит учесть, что пользовательская функция должна возвращать:

  • положительное число (в основном выбирают 1), если первый указанный элемент следует за вторым при сравнении;
  • отрицательное число (обычно -1), если второй выбранный элемент должен следовать за первым;
  • нуль, если два проверяемых значения равны.

В качестве примера давайте первоначальный массив results отсортируем по очкам. При чем результаты будут упорядочены от большего к меньшему. Это можно реализовать двумя способами.

В первом варианте я изменил логику сортировки, т.е. в ситуации, когда надо возвращать положительное число, возвращаю отрицательное и наоборот.

Рекордная таблица:

var results = [ ["Маркус", 333], ["Наташа", 211], ["Алексей", 124] ]; results.sort(RecordSort); function RecordSort(a, b) { if (a > b) return -1; else if (a < b) return 1; else return 0; } for(var i=0; i b) return 1; else if (a < b) return -1; else return 0; }

function RecordSort(a, b) { if (a > b) return 1; else if (a < b) return -1; else return 0; }

А вот после нее добавим указанный выше метод.

Вывод производится аналогичным образом.

Хочу обратить ваше внимание на один важный момент. При использовании данных функций все изменения происходят с массивом, к которому вы их применяете. Таким образом, если вам необходимо сохранить первоначальный вид данных, то создавайте копию, а после редактируйте уже ее.

Ну, вот я и рассказал о многомерных массивах и их сортировке. Если вам понравилась статья, то подписывайтесь на блог и читайте другие не менее интересные публикации. Буду благодарен за репосты. До новых встреч!

Пока-пока!

С уважением, Роман Чуешов

Прочитано: 136 раз

The sort() method sorts the elements of an array in place and returns the array. The default sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

The time and space complexity of the sort cannot be guaranteed as it is implementation dependent.

The source for this interactive example is stored in a GitHub repository. If you"d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax arr .sort() Parameters compareFunction Optional Specifies a function that defines the sort order. If omitted, the array is sorted according to each character"s Unicode code point value, according to the string conversion of each element. firstEl The first element for comparison. secondEl The second element for comparison. Return value

The sorted array. Note that the array is sorted in place , and no copy is made.

Description

If compareFunction is not supplied, all non- undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order. All undefined elements are sorted to the end of the array.

Note: In UTF-16, Unicode characters above \uFFFF are encoded as two surrogate code units, of the range \uD800 - \uDFFF . The value of each code unit is taken separately into account for the comparison. Thus the character formed by the surrogate pair \uD655\uDE55 will be sorted before the character \uFF3A .

If compareFunction is supplied, all non- undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFunction). If a and b are two elements being compared, then:

  • If compareFunction(a, b) is less than 0, sort a to an index lower than b (i.e. a comes first).
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to an index lower than a (i.e. b comes first).
  • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.

So, the compare function has the following form:

Function compare(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; }

To compare numbers instead of strings, the compare function can simply subtract b from a . The following function will sort the array ascending (if it doesn"t contain Infinity and NaN):

Function compareNumbers(a, b) { return a - b; } var numbers = ; numbers.sort(function(a, b) { return a - b; }); console.log(numbers); //

ES2015 provides arrow function expressions with even shorter syntax.

Let numbers = ; numbers.sort((a, b) => a - b); console.log(numbers); //

Objects can be sorted given the value of one of their properties.

Var items = [ { name: "Edward", value: 21 }, { name: "Sharpe", value: 37 }, { name: "And", value: 45 }, { name: "The", value: -12 }, { name: "Magnetic", value: 13 }, { name: "Zeros", value: 37 } ]; // sort by value items.sort(function (a, b) { return a.value - b.value; }); // sort by name items.sort(function(a, b) { var nameA = a.name.toUpperCase(); // ignore upper and lowercase var nameB = b.name.toUpperCase(); // ignore upper and lowercase if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } // names must be equal return 0; });

Examples Creating, displaying, and sorting an array

The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without, then with, a compare function.

Var stringArray = ["Blue", "Humpback", "Beluga"]; var numericStringArray = ["80", "9", "700"]; var numberArray = ; var mixedNumericArray = ["80", "9", "700", 40, 1, 5, 200]; function compareNumbers(a, b) { return a - b; } console.log("stringArray:", stringArray.join()); console.log("Sorted:", stringArray.sort()); console.log("numberArray:", numberArray.join()); console.log("Sorted without a compare function:", numberArray.sort()); console.log("Sorted with compareNumbers:", numberArray.sort(compareNumbers)); console.log("numericStringArray:", numericStringArray.join()); console.log("Sorted without a compare function:", numericStringArray.sort()); console.log("Sorted with compareNumbers:", numericStringArray.sort(compareNumbers)); console.log("mixedNumericArray:", mixedNumericArray.join()); console.log("Sorted without a compare function:", mixedNumericArray.sort()); console.log("Sorted with compareNumbers:", mixedNumericArray.sort(compareNumbers));

This example produces the following output. As the output shows, when a compare function is used, numbers sort correctly whether they are numbers or numeric strings.

StringArray: Blue,Humpback,Beluga Sorted: Beluga,Blue,Humpback numberArray: 40,1,5,200 Sorted without a compare function: 1,200,40,5 Sorted with compareNumbers: 1,5,40,200 numericStringArray: 80,9,700 Sorted without a compare function: 700,80,9 Sorted with compareNumbers: 9,80,700 mixedNumericArray: 80,9,700,40,1,5,200 Sorted without a compare function: 1,200,40,5,700,80,9 Sorted with compareNumbers: 1,5,9,40,80,200,700

Sorting non-ASCII characters

For sorting strings with non-ASCII characters, i.e. strings with accented characters (e, é, è, a, ä, etc.), strings from languages other than English: use String.localeCompare . This function can compare those characters so they appear in the right order.

Var items = ["réservé", "premier", "cliché", "communiqué", "café", "adieu"]; items.sort(function (a, b) { return a.localeCompare(b); }); // items is ["adieu", "café", "cliché", "communiqué", "premier", "réservé"]

Sorting with map

The compareFunction can be invoked multiple times per element within the array. Depending on the compareFunction "s nature, this may yield a high overhead. The more work a compareFunction does and the more elements there are to sort, the wiser it may be to consider using a map for sorting. The idea is to traverse the array once to extract the actual values used for sorting into a temporary array, sort the temporary array and then traverse the temporary array to achieve the right order.

// the array to be sorted var list = ["Delta", "alpha", "CHARLIE", "bravo"]; // temporary array holds objects with position and sort-value var mapped = list.map(function(el, i) { return { index: i, value: el.toLowerCase() }; }) // sorting the mapped array containing the reduced values mapped.sort(function(a, b) { if (a.value > b.value) { return 1; } if (a.value < b.value) { return -1; } return 0; }); // container for the resulting order var result = mapped.map(function(el){ return list; });

Specifications Specification Status Comment
ECMAScript 1st Edition (ECMA-262) Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
Standard
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of "Array.prototype.sort" in that specification.
Standard
ECMAScript Latest Draft (ECMA-262)
The definition of "Array.prototype.sort" in that specification.
Draft
Browser compatibility

The compatibility table in this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js sort
Chrome Full support 1 Edge Full support 12 Firefox Full support 1 IE Full support 5.5 Opera Full support Yes Safari Full support Yes WebView Android Full support Yes Chrome Android Full support Yes Edge Mobile Full support Yes Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support Yes nodejs Full support Yes

В JavaScript можно сортировать массивы с помощью метода sort. В качестве единственного необязательного аргумента метод принимает функцию, определяющую правила сортировки. Если sort вызвали без аргументов, то сортировка осуществляется по возрастанию значений элементов. Пример:

// Массив со значениями различных типов var arr = ; // Сортируем arr.sort(); // Вернет

Сортируется массив, в контексте которого вызван метод, так что если вы желаете сохранить исходное состояние - сделайте копию и сортируйте её.
Функции сортировки

Вы можете настраивать сортировку, передавая методу sort специальную функцию. В качестве аргументов функция принимает два значения массива, которые передаст метод sort. Вернуть функция может следующие значения (спасибо за уточнение пользователю alik):

* положительное (1,2,10), если условие сортировки истинно;
* отрицательное (-0.1, -3, -20), если условие сортировки ложно;
* 0, если сравниваемые значения равны.

var arr = ; // Функции сортировки function sIncrease(i, ii) { // По возрастанию if (i > ii) return 1; else if (i < ii) return -1; else return 0; } function sDecrease(i, ii) { // По убыванию if (i > ii) return -1; else if (i < ii) return 1; else return 0; } function sRand() { // Случайная return Math.random() > 0.5 ? 1: -1; } arr.sort(sIncrease); // Вернет arr.sort(sDecrease); // Вернет arr.sort(sRand); // Вернет случайно отсортированный массив, например

Производительность

На первый взгляд может показаться, что сортировка в JavaScript непроизводительна, и в web-приложениях лучше сортировать данные на server-side. Небольшой эксперимент это опровергает. Будьте осторожны, в циклах на 100.000 элементов браузер может зависнуть!

Сортируем массивы c целочисленными значениями различной длины:
Нет данных

можете зависнуть

Автор, в ходе своих экспериментов на своем PC (Vista, Pentium Dual 2.2Ггц, 2Гб RAM) получил следующие результаты:
1000 10.000 100.000
IE 7 20-50 ms 200-650 ms завис
FF 3 1-2 ms 12-30 ms 150-400 ms
Safari 3 2-30 ms * 30-400 ms * 350-5000 ms *
Opera 9.5 2-5 ms 40-75 ms 500-1000 ms
Chrome 1.0 1-2 ms 10-30 ms 100-300ms

* В Safari случайная сортировка занимала ровно на порядок больше времени, чем сортировка по возрастанию/убыванию.

За исключением Internet Explorer, который не смог переварить массив на 100.000 элементов, сортировка показала себя вполне производительной операцией.
Многомерный массив

При необходимости можно усложнить функции сортировки. Например, чтобы сортировать многомерные массивы (массивы массивов), или массивы объектов, или любой другой массив с нетривиальными значениями. Пример:

var multi = [ ["Nikolay", 34], ["Andrey", 23], ["Stanislav", 20] ]; // Функции сортировки function sName(i, ii) { // По имени (возрастание) if (i > ii) return 1; else if (i < ii) return -1; else return 0; } function sAge(i, ii) { // По возрасту (возрастание) if (i > ii) return 1; else if (i < ii) return -1; else return 0; } multi.sort(sName); // Вернет [,,] multi.sort(sAge); // Вернет [,,]

Хорошо Плохо

    Благодаря своей мощности и гибкости в работе массивы стали непременным атрибутом PHP. Причем, в ряде сложных ситуаций можно задействовать и двумерные массивы PHP.…

    Сортировка данных - обязательная функция для сайта, если на нем есть контент, отображаемый в виде таблицы. Для удобства пользователя необходимо сделать таблицу…

.

Большинство дискуссий по поводу алгоритмов сортировки, как правило, заканчиваются обсуждением алгоритма быстрой сортировки из-за его скорости. Курсы информатики, как правило, охватывают quicksort потому, что он имеет отличный показатель средней сложности O(n log n) и относительно высокую производительность по сравнению с другими, менее эффективными алгоритмами вроде buble sort или insert sort для больших наборов данных. В отличие от других алгоритмов сортировки, существует множество различных реализаций quicksort, одни направлены на повышение производительности, другие - на устойчивость (эквивалентные элементы, остаются в том же порядке, в котором они изначально встречаются).

Быстрая сортировка - это “разделяй и властвуй” алгоритм в стиле “сортировка слиянием”. Основная идея заключается в том, чтобы найти опорный элемент в массиве для сравнения с остальными частями, затем сдвигать элементы так, чтобы все части перед опорным элементом были меньше его, а все элементы после опорного были больше его. После этого рекурсивно выполнить ту же операцию на элементы до и после опорного. Существует множество различных алгоритмов для достижения быстрой сортировки, в этой статье рассматривается только один из них.

Существует две базовые операции в алгоритме: замена элемента на месте и разбиение массива на части. Основные шаги для разделения массива:

  • Найти опорный элемент в массиве. Этот элемент - основа для сравнения за одни проход.
  • Установить указатель (левый указатель) с первого элемента в массиве.
  • Установить указатель (правый указатель) с последнего элемента в массиве.
  • Пока значение левого указателя в массиве меньше, чем значение опорного элемента, сдвигать левый указатель вправо (добавить 1). Продолжить пока значение левого указателя не станет большим или равным опорному.
  • Пока значение правого указателя в массиве больше, чем значение опорного элемента, сдвигать правый указатель влево (вычитать 1). Продолжать пока значение правого указателя не станет меньшим или равным значению разделителя.
  • Если левый указатель меньше или равен правому указателю, поменять значения в этих местах в массиве.
  • Сдвинуть левый указатель вправо на одну позицию и правый указатель на одну позицию влево.
  • Если левый указатель и правый указатель не встретятся, перейти к шагу 1.
  • Как и многие другие алгоритмы, эти распределения проще понять, глядя на пример. Предположим, у вас есть следующий массив:

    Var items = ;

    Существует множество способов найти значение разделителя. Некоторые алгоритмы берут первый элемент в качестве опорного. Это не самый лучший выбор, потому что он дает наихудшие показатели для уже отсортированных массивов. Лучше взять в качестве разделителя элемент из середины, для нас разделителем будет 5 (длинна массива, разделенная на 2). Далее установим левый указатель на нулевую позицию и правый указатель на позицию 5 (последний элемент в массиве). Поскольку 4 меньше 5, переместим левый указатель на 1 позицию. Поскольку 2 меньше 5, переместим левый указатель во вторую позицию. Сейчас 6 не меньше 5, перестаем сдвигать левый указатель и начинаем сдвигать правый. Так как 9 больше 5, правый указатель перемещаем на позицию 4. Значение 3 не больше 5, поэтому правый указатель останавливается. Поскольку левый указатель находится в положении 2, а правый указатель в положении 4, и эти два элемента не встречались, значения 6 и 3 должны быть поменяны местами.

    Далее, левый указатель увеличивается на единицу, а правый уменьшается на единицу. В обоих случаях значение будет равно опорному элементу (5). Это сигнализирует, что операция завершена. Теперь все элементы в массиве слева от разделителя меньше, чем сам разделитель и все элементы справа от разделителя больше него самого. Имейте в виду, что это не значит, что массив уже отсортирован, только то, что есть две части массива: секция, где все значения меньше, чем опорный элемент, и секции, где все значения больше опорного элемента. Смотрим рисунок ниже:

    Реализация функции разбиения использует функцию swop() , код этой функции:

    Function swap(items, firstIndex, secondIndex){
    const temp = items;
    items = items;
    items = temp;
    }

    Функция разделитель сама по себе довольно проста и следующий алгоритм почти точен.

    Function partition(items, left, right) { var pivot = items,
    i = left,
    j = right;

    While (i pivot) {
    j--;
    } if (i 1) { index = partition(items, left, right); if (left < index - 1) {
    } if (index < right) {
    } } return items;
    }

    // first call
    var result = quickSort(items, 0, items.length - 1);

    Функция quicksort() принимает три аргумента: массив для сортировки, индекс для установки левого указателя и индекс для установки правого указателя. Для оптимизации производительности, массив не будет отсортирован, если у него ноль или один элемент. Если в массиве два или более элементов, он является "разбиваемым". Если left меньше, чем возвращенный index минус единица, то слева еще остались элементы для сортировки и функция quickSort() вызывается для них рекурсивно. Аналогичным образом, если index меньше правого указателя, то элементы справа сортируются. Как только все это сделано, массив возвращается в качестве результата.

    Для того, чтобы эта функция стала немного удобней для пользователей, вы можете автоматически заполнить значения по умолчанию для left и right указателей, если они не передаются, например:

    Function quickSort(items, left, right) { var index; if (items.length > 1) { left = typeof left != "number" ? 0: left;
    right = typeof right != "number" ? items.length - 1: right; index = partition(items, left, right); if (left < index - 1) {
    quickSort(items, left, index - 1);
    } if (index < right) {
    quickSort(items, index, right);
    } } return items;
    } // first call
    var result = quickSort(items);

    В этой версии функции можно не указывать начальные left и right , так как они заполняются автоматически, если не были переданы. Это делает функцию чуть более удобной, чем чистая реализация.

    Quicksort, как правило, считается самой эффективной и быстрой и поэтому используется в V8 как реализация Array.prototype.sort() для массивов с более чем 23 элементами. Для менее чем 23 элемента в V8 используется insertion sort . Merge sort - конкурент quicksort, аналогично ему он также эффективный и быстрый, но имеет дополнительное преимущество - устойчивость. Поэтому Mozilla и Safari используют его для имплементации Array.prototype.sort() .

    The sort() method sorts the elements of an array in place and returns the array. The default sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

    The time and space complexity of the sort cannot be guaranteed as it is implementation dependent.

    The source for this interactive example is stored in a GitHub repository. If you"d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

    Syntax arr .sort() Parameters compareFunction Optional Specifies a function that defines the sort order. If omitted, the array is sorted according to each character"s Unicode code point value, according to the string conversion of each element. firstEl The first element for comparison. secondEl The second element for comparison. Return value

    The sorted array. Note that the array is sorted in place , and no copy is made.

    Description

    If compareFunction is not supplied, all non- undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order. All undefined elements are sorted to the end of the array.

    Note: In UTF-16, Unicode characters above \uFFFF are encoded as two surrogate code units, of the range \uD800 - \uDFFF . The value of each code unit is taken separately into account for the comparison. Thus the character formed by the surrogate pair \uD655\uDE55 will be sorted before the character \uFF3A .

    If compareFunction is supplied, all non- undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFunction). If a and b are two elements being compared, then:

    • If compareFunction(a, b) is less than 0, sort a to an index lower than b (i.e. a comes first).
    • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
    • If compareFunction(a, b) is greater than 0, sort b to an index lower than a (i.e. b comes first).
    • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.

    So, the compare function has the following form:

    Function compare(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; }

    To compare numbers instead of strings, the compare function can simply subtract b from a . The following function will sort the array ascending (if it doesn"t contain Infinity and NaN):

    Function compareNumbers(a, b) { return a - b; } var numbers = ; numbers.sort(function(a, b) { return a - b; }); console.log(numbers); //

    ES2015 provides arrow function expressions with even shorter syntax.

    Let numbers = ; numbers.sort((a, b) => a - b); console.log(numbers); //

    Objects can be sorted given the value of one of their properties.

    Var items = [ { name: "Edward", value: 21 }, { name: "Sharpe", value: 37 }, { name: "And", value: 45 }, { name: "The", value: -12 }, { name: "Magnetic", value: 13 }, { name: "Zeros", value: 37 } ]; // sort by value items.sort(function (a, b) { return a.value - b.value; }); // sort by name items.sort(function(a, b) { var nameA = a.name.toUpperCase(); // ignore upper and lowercase var nameB = b.name.toUpperCase(); // ignore upper and lowercase if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } // names must be equal return 0; });

    Examples Creating, displaying, and sorting an array

    The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without, then with, a compare function.

    Var stringArray = ["Blue", "Humpback", "Beluga"]; var numericStringArray = ["80", "9", "700"]; var numberArray = ; var mixedNumericArray = ["80", "9", "700", 40, 1, 5, 200]; function compareNumbers(a, b) { return a - b; } console.log("stringArray:", stringArray.join()); console.log("Sorted:", stringArray.sort()); console.log("numberArray:", numberArray.join()); console.log("Sorted without a compare function:", numberArray.sort()); console.log("Sorted with compareNumbers:", numberArray.sort(compareNumbers)); console.log("numericStringArray:", numericStringArray.join()); console.log("Sorted without a compare function:", numericStringArray.sort()); console.log("Sorted with compareNumbers:", numericStringArray.sort(compareNumbers)); console.log("mixedNumericArray:", mixedNumericArray.join()); console.log("Sorted without a compare function:", mixedNumericArray.sort()); console.log("Sorted with compareNumbers:", mixedNumericArray.sort(compareNumbers));

    This example produces the following output. As the output shows, when a compare function is used, numbers sort correctly whether they are numbers or numeric strings.

    StringArray: Blue,Humpback,Beluga Sorted: Beluga,Blue,Humpback numberArray: 40,1,5,200 Sorted without a compare function: 1,200,40,5 Sorted with compareNumbers: 1,5,40,200 numericStringArray: 80,9,700 Sorted without a compare function: 700,80,9 Sorted with compareNumbers: 9,80,700 mixedNumericArray: 80,9,700,40,1,5,200 Sorted without a compare function: 1,200,40,5,700,80,9 Sorted with compareNumbers: 1,5,9,40,80,200,700

    Sorting non-ASCII characters

    For sorting strings with non-ASCII characters, i.e. strings with accented characters (e, é, è, a, ä, etc.), strings from languages other than English: use String.localeCompare . This function can compare those characters so they appear in the right order.

    Var items = ["réservé", "premier", "cliché", "communiqué", "café", "adieu"]; items.sort(function (a, b) { return a.localeCompare(b); }); // items is ["adieu", "café", "cliché", "communiqué", "premier", "réservé"]

    Sorting with map

    The compareFunction can be invoked multiple times per element within the array. Depending on the compareFunction "s nature, this may yield a high overhead. The more work a compareFunction does and the more elements there are to sort, the wiser it may be to consider using a map for sorting. The idea is to traverse the array once to extract the actual values used for sorting into a temporary array, sort the temporary array and then traverse the temporary array to achieve the right order.

    // the array to be sorted var list = ["Delta", "alpha", "CHARLIE", "bravo"]; // temporary array holds objects with position and sort-value var mapped = list.map(function(el, i) { return { index: i, value: el.toLowerCase() }; }) // sorting the mapped array containing the reduced values mapped.sort(function(a, b) { if (a.value > b.value) { return 1; } if (a.value < b.value) { return -1; } return 0; }); // container for the resulting order var result = mapped.map(function(el){ return list; });

    Specifications Specification Status Comment
    ECMAScript 1st Edition (ECMA-262) Standard Initial definition.
    ECMAScript 5.1 (ECMA-262)
    Standard
    ECMAScript 2015 (6th Edition, ECMA-262)
    The definition of "Array.prototype.sort" in that specification.
    Standard
    ECMAScript Latest Draft (ECMA-262)
    The definition of "Array.prototype.sort" in that specification.
    Draft
    Browser compatibility

    The compatibility table in this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

    Update compatibility data on GitHub

    Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js sort
    Chrome Full support 1 Edge Full support 12 Firefox Full support 1 IE Full support 5.5 Opera Full support Yes Safari Full support Yes WebView Android Full support Yes Chrome Android Full support Yes Edge Mobile Full support Yes Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support Yes nodejs Full support Yes