2724. Sort By
Add a method sortBy(fn) to arrays in JavaScript. The method should return a new array sorted in ascending order based on the result of applying the function fn to each element.
📄 Problem Statement
Given an array arr and a function fn, return a new array sortedArr. The array should be sorted in ascending order based on the value returned by fn for each element.
- Assume
fnonly returns numbers. - Assume no two elements will return the same number when
fnis applied. - Do not modify the original array.
💡 Example
[5, 4, 1, 2, 3].sortBy(x => x)
// ➞ [1, 2, 3, 4, 5]
[{"x": 1}, {"x": 0}, {"x": 5}].sortBy(obj => obj.x)
// ➞ [{"x": 0}, {"x": 1}, {"x": 5}]
🧠 Explanation
The function creates a shallow copy of the original array using slice() or spread syntax, then sorts that copy using JavaScript’s built-in sort method with a custom comparator based on fn.
✅ Your Solution
/**
* @param {Function} fn
* @return {Array}
*/
Array.prototype.sortBy = function(fn) {
return [...this].sort((a, b) => fn(a) - fn(b));
};