How to implement Array.prototype.sort? JavaScript Interview Question | Problem Solving | JavaScript Polyfills
In this question, the candidate needs to implement a function customSort
that mimics the behaviour of Array.prototype.sort
method.
More about Array.prototype.sort
The reverse()
method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.
Examples
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
const numbers = [1, 30, 4, 21, 100000];
numbers.sort();
console.log(numbers);
// expected output: Array [1, 100000, 21, 30, 4]
Syntax
// Functionless
sort()
// Arrow function
sort((a, b) => { /* … */ } )
// Compare function
sort(compareFn)
// Inline compare function
sort(function compareFn(a, b) { /* … */ })
Parameters
compareFn
(Optional)
Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.
a
The first element for comparison.
b
The second element for comparison.
Return value
The reference to the original array, now sorted. Note that the array is sorted in place, and no copy is made.
Submission
Start the timer, complete your solution, and test it against the test cases provided by the platform. Ideally, you should finish this question within 30 mins. Share your solution with us -- https://twitter.com/devtoolstech