2724. Sort By
IntuitionApproachExplanation:
1- Copying the Array:arr.slice() creates a shallow copy of the original array. This ensures the original array remains unchanged d
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Explanation:**\n1- Copying the Array:\n\n**arr.slice()** creates a shallow copy of the original array. This ensures the original array remains unchanged during the sort operation.\n\n2- Sorting Logic:\n**.sort((a, b) => fn(a) - fn(b))** sorts the copied array. The sort function compares elements a and b by applying the function fn to each element:\n\nIf **fn(a) < fn(b)**, the result is negative, and a comes before b.\n\nIf **fn(a) > fn(b)**, the result is positive, and a comes after b.\n\nIf **fn(a) === fn(b)**, the result is zero, and the order remains unchanged.\n\n# Complexity\n- Time complexity:- O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:- O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Array} arr\n * @param {Function} fn\n * @return {Array}\n */\nvar sortBy = function(arr, fn) {\n    //bas array ko sort krna h chote se function se slice methode array ke copy return krta h \n    return arr.slice().sort((a, b) => fn(a) - fn(b)) // a>b to negative result \n    \n\n};\n```
['JavaScript']