2724. Sort By - Just 01 line - Beats 95.81% of users with JavaScript (Runtime)
Intuition\nThe problem requires sorting an array based on the values returned by a given function. The sorting should be done in ascending order according to th
# Intuition\nThe problem requires sorting an array based on the values returned by a given function. The sorting should be done in ascending order according to the function outputs.\n\n# Approach\nThe approach involves creating a shallow copy of the input array using `slice()`. This is done to avoid modifying the original array. The `sort()` method is then applied to the copied array, using a custom comparison function. The comparison function compares the values returned by the provided function (`fn`) for each element, ensuring the sorted order based on these values.\n\n# Complexity\n- Time complexity: O(n * log(n)) \n  - The `slice()` operation takes O(n) time, and the subsequent `sort()` operation takes O(n * log(n)) time in the worst case.\n- Space complexity: O(n)\n  - The shallow copy created using `slice()` requires O(n) space.\n\n# Code\n```javascript\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n    return arr.slice().sort((a, b) => fn(a) - fn(b));\n};\n```
['JavaScript']