Sort By simple solution ✅🚀
IntuitionSorting an array based on a computed value for each element is a common task.
The sortBy function takes an array and a callback function (fn), which de
# Intuition
Sorting an array based on a computed value for each element is a common task.

- The `sortBy` function takes an array and a callback function (`fn`), which determines the sort key for each element.
- The key idea is to compare elements based on the value returned by the callback function.
# Approach
- **Use JavaScript's `Array.prototype.sort`**:
    - The `sort` method sorts elements in place and accepts a comparator function.
- **Define the Comparator Function**:
    - For each pair of elements, apply the callback function (`fn`) to compute their respective sort keys.
    - Compare the keys:
        - If the key for the first element is smaller, return `1`.
        - If the key for the second element is smaller, return `1`.
        - If both keys are equal, return `0`.
- **Return the Sorted Array**:
    - The `sort` method rearranges the elements based on the comparator logic and returns the sorted array.
# Complexity
- Time complexity:
  -  Sorting Complexity: Sorting involves comparisons, leading to a time complexity of 
𝑂(𝑛log
  - ⁡Key Calculation: The callback function (fn) is called for each comparison, which happens 
𝑂(𝑛log𝑛)O(nlogn) times.


- Space complexity:
   - Sorting is done in place, so no extra space is required for the array itself. However, the function calls for fn may require stack space depending on its implementation.
# Code
```javascript []
/**
 * @param {Array} arr
 * @param {Function} fn
 * @return {Array}
 */
var sortBy = function(arr, fn) {
    function swap(a, b) {
        return (fn(a) < fn(b)) ? -1 : 1
    }

    return arr.sort(swap)
};
```
['JavaScript']