[Easy] LeetCode JS 30 - 2724. Sort By

March 8, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2724. Sort By

Question 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 sortedArrsortedArray 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

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 before b.
  • A positive value if b should come before a.
  • Zero if the order of a and b 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) and fn(b) to calculate the sorting values for each element.
  • The heart of the logic lies in return fnResultA - fnResultB. This tells the sort method how to order the elements:
    • If the result is negative, a should come before b.
    • If the result is positive, b should come before a.
    • If the result is zero, the order of a and b doesn't change.
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

function sortBy(arr, fn) {
  return arr.sort((a, b) => fn(a) - fn(b));
}
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee