JavaScript Array Operations: Sort

node v16.18.0
version: 1.0.0
endpointsharetweet
Sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
/** * Sorts numbers in ascending order * * @param {any} firstElem - The first element for comparison. * @param {any} secondElem - The second element for comparison. */ function numberComparator (firstElem, secondElem) { /* return comparison result */ return firstElem - secondElem; } /** * Sorts strings in descending order * * @param {any} firstElem - The first element for comparison. * @param {any} secondElem - The second element for comparison. */ function stringComparator (firstElem, secondElem) { if (firstElem < secondElem) return 1; if (firstElem > secondElem) return -1; return 0; } // Let's start with an array of numbers const numbers = [3, 2, 1, 15, 4, 10, 5];
numbers.sort(); // By default it convert elements into strings
numbers.sort(numberComparator); // Using the right comparator we have the expected results
// Let's sort an array of strings const strings = ["Banana", "Apple", "Tangerine", "Cherry"];
strings.sort(); // By default it sorts strings in ascending order
strings.sort(stringComparator); // Using the right comparator we have the expected results
Loading…

no comments

    sign in to comment