DEV Community

seri0009
seri0009

Posted on

Array.prototype.sort()

sort() is a static method of Array which 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..

So what is a static method?

-A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor Methods called on object instances are called instance method.

sort() takes in a compare function with two arguments which compares two values and orders accordingly

  • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments which can be a string or a number strings are compared based on UTF number based off of reminder.

syntax : sort(compare(a, b))

Example :

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;
}

-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).

  • A sort Method can be called without passing a compare function (Function Less) with default order as ascending.

Syntax : sort()

Example :

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

Sorting with Map :

The more work a compareFunction does and the more elements there are to sort, it may be more efficient to use 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.

Example :

// the array to be sorted
const data = ['delta', 'alpha', 'charlie', 'bravo'];

// temporary array holds objects with position and sort-value
const mapped = data.map((v, i) => {
return { i, value: someSlowOperation(v) };
})

// sorting the mapped array containing the reduced values

mapped.sort((a, b) => {
if (a.value > b.value) {
return 1;
}
if (a.value < b.value) {
return -1;
}
return 0;
});

const result = mapped.map(v => data[v.i]);

Time Complexity :

The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.

Compatibility :

Other than Internet Explorer sort() works on every browser, mobile and pc also Dino and Node.js.

Discussion (0)