JavaScript Sort By
Intuition\n Describe your first thoughts on how to solve this problem. \nWe need to return a sorted array, where the sorting is based on the output of a given f
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to return a sorted array, where the sorting is based on the output of a given function, which exclusively returns numbers, ensuring the sorted array is in ascending order according to the function\'s output.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. These are comment delimiters for a multi-line comment to help explain and document code while preventing ignored text from executing. These comments are commonly used in formal documentation for better code understanding.\n\n    ```\n    /**\n    * Multi-line comment\n    */\n    ```\n\n2. This is a special type of comment called a JSDoc comment that explains that the function should take parameters named `arr` and `fn`, which are expected to be an `Array` and a `Function`.\n\n    ```\n    @param {Array} arr\n    @param {Function} fn\n    ```\n\n3. This is a special type of comment called a JSDoc comment that explains what the code should return, which, in this case, is an `Array`. It helps developers and tools like code editors and documentation generators know what the function is supposed to produce.\n\n    ```\n    @return {Array}\n    ```\n\n4. This is how we define a function named `sortBy` that takes an array `arr` and a function `fn` as its arguments.\n\n    ```\n    var sortBy = function(arr, fn) {\n        // code to be executed\n    };\n    ```\n\n5. This function returns the array sorted in ascending order, where the sorting is determined by the output of the function `fn` applied to each element (`a` and `b`).\n\n    ```\n    return arr.sort((a, b) => fn(a) - fn(b));\n    ```\n\n# Complexity\n- Time complexity: $O(n log n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`n` is the length of the input array. This is because the function uses the `sort` method, which has a time complexity of $O(n log n)$ in the average case.\n\n- Space complexity: $O(1)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThis is because the function does not use any additional data structures that grow with the size of the input array.\n\n# Code\n```\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n    return arr.sort((a, b) => fn(a) - fn(b));\n};\n```
['JavaScript']