|
| 1 | +// Question Link: https://leetcode.com/problems/sort-by/description/?envType=study-plan-v2&envId=30-days-of-javascript |
| 2 | +// Solution Link: https://leetcode.com/problems/sort-by/solutions/5446437/javascript-easy-solution-one-line-code/ |
| 3 | + |
| 4 | +/* |
| 5 | +2724. Sort By |
| 6 | +
|
| 7 | +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. |
| 8 | +
|
| 9 | +You may assume that fn will never duplicate numbers for a given array. |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +Input: arr = [5, 4, 1, 2, 3], fn = (x) => x |
| 13 | +Output: [1, 2, 3, 4, 5] |
| 14 | +Explanation: fn simply returns the number passed to it so the array is sorted in ascending order. |
| 15 | +
|
| 16 | +Example 2: |
| 17 | +Input: arr = [{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x |
| 18 | +Output: [{"x": -1}, {"x": 0}, {"x": 1}] |
| 19 | +Explanation: fn returns the value for the "x" key. So the array is sorted based on that value. |
| 20 | +
|
| 21 | +Example 3: |
| 22 | +Input: arr = [[3, 4], [5, 2], [10, 1]], fn = (x) => x[1] |
| 23 | +Output: [[10, 1], [5, 2], [3, 4]] |
| 24 | +Explanation: arr is sorted in ascending order by number at index=1. |
| 25 | +
|
| 26 | +Constraints: |
| 27 | +arr is a valid JSON array |
| 28 | +fn is a function that returns a number |
| 29 | +1 <= arr.length <= 5 * 10^5 |
| 30 | +*/ |
| 31 | + |
| 32 | + |
| 33 | + |
| 34 | +/** |
| 35 | + * @param {Array} arr |
| 36 | + * @param {Function} fn |
| 37 | + * @return {Array} |
| 38 | + */ |
| 39 | + |
| 40 | +var sortBy = function(arr, fn) { |
| 41 | + return arr.sort((a, b) => fn(a) - fn(b)); |
| 42 | +}; |
0 commit comments