#JS30: 18 (JSON - 4)
Intuition\n Describe your first thoughts on how to solve this problem. \n- Solve using the built-in array method - array.toSorted(compareFunction(a,b)) . the di
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Solve using the built-in array method - `array.toSorted(compareFunction(a,b))` . the different between it and `array.sort(compareFunction(a,b))` is `toSorted` will return a new array and kept original array; While `sort` wil modify on the original array.\n\n- `compareFunction(a,b)` define, how the elements will be rearrange by compare pairs of elements in the array. \n\n- The function takes two arguments, `a` and `b`, which represent two elements from the array that are being compared.\n\n- The return value of the callback function determines the `order of a and b`:\n1. If the return value is less than 0: a comes before b.\n2. If the return value is greater than 0: b comes before a.\n3. If the return value is 0: The order of a and b remains unchanged.\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.toSorted((a, b) => fn(a) - fn(b));\n};\n```
['JavaScript']