[Easy] LeetCode JS 30 - 2724. Sort By
March 8, 2024
LeetCode 30 Days of JavaScript
This question is from LeetCode's 30 Days of JavaScript Challenge
2724. Sort ByQuestion Prompt
Given an array arr
and a function fn
, return a sorted array sortedArr
. You can assume fn
only returns numbers and those numbers determine the sort order of sortedArr
. sortedArray
must be sorted in ascending order by fn
output.
You may assume that fn
will never duplicate numbers for a given array.
// Example 1:
Input: arr = [5, 4, 1, 2, 3], fn = (x) => x
Output: [1, 2, 3, 4, 5]
Explanation: fn simply returns the number passed to it so the array is sorted in ascending order.
// Example 2:
Input: arr = [{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x
Output: [{"x": -1}, {"x": 0}, {"x": 1}]
Explanation: fn returns the value for the "x" key. So the array is sorted based on that value.
Solutions
Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!
Before solving this question, we need to understand the sort
method in JavaScript. JavaScript's Array.prototype.sort
accepts an optional comparator function to define custom sorting logic.
The comparator takes two elements from the array, a
and b
, and should return:
- A negative value if
a
should come beforeb
. - A positive value if
b
should come beforea
. - Zero if the order of
a
andb
doesn't matter.
That is to say, the following is ascending
function ascendingCompareFn(a, b) {
return a - b;
}
And for descending, it will be
function descendingCompareFn(a, b) {
return b - a;
}
Back to the question, the comparator function passed to sort
receives two elements (a
and b
) from the array at a time.
- Inside the comparator, we call
fn(a)
andfn(b)
to calculate the sorting values for each element. - The heart of the logic lies in
return fnResultA - fnResultB
. This tells thesort
method how to order the elements:- If the result is negative,
a
should come beforeb
. - If the result is positive,
b
should come beforea
. - If the result is zero, the order of
a
andb
doesn't change.
- If the result is negative,
function sortBy(arr, fn) {
return arr.sort((a, b) => {
const fnResultA = fn(a);
const fnResultB = fn(b);
// Ascending order:
return fnResultA - fnResultB;
});
}
Or we could write it in a more concise syntax like this
function sortBy(arr, fn) {
return arr.sort((a, b) => fn(a) - fn(b));
}