Sort Array by Custom Comparator in JavaScript

Day 24/30 – Sort an Array by Function Output in JavaScript Challange🔢 | Custom Comparator 📌 Problem Given: An array arr A function fn Return a new array sortedArr sorted in ascending order based on the value returned by fn(arr[i]). You can assume: fn always returns a number Sorting must be based on fn output 🧠 Example arr = [5, 4, 1, 2, 3] fn = (x) => x * x Since squares are: 25, 16, 1, 4, 9 Sorted by square value: [1, 2, 3, 4, 5] 💡 JavaScript Solution var sortBy = function(arr, fn) { return arr.slice().sort((a, b) => fn(a) - fn(b)); }; 🔎 Why This Works sort() accepts a comparator fn(a) - fn(b) ensures ascending order slice() prevents mutation of the original array Time Complexity: O(n log n) Space Complexity: O(n) (due to copy) ⚡ Real-World Use Cases Sorting users by age Sorting products by price Ranking students by score Sorting tasks by priority 🧠 Interview Insight This pattern is called “sort by projection”: You don’t sort by the element itself — You sort by a derived value. That’s a powerful abstraction concept. #JavaScript #30DaysOfJavaScript #CodingChallenge #JSLogic #ArrayMethods #WebDevelopment #FrontendDevelopment #LearnToCode #CodeEveryday #Programming #DeveloperJourney #TechCommunity #InterviewPrep #LeetCode #AsyncJavaScript #SoftwareEngineering #100DaysOfCode #BuildInPublic Custom comparator JavaScript Sort array by derived value JS JavaScript array sort interview question Higher order functions JavaScript JavaScript sorting techniques JS sort with callback Advanced JavaScript array methods JavaScript coding challenge solution Frontend interview preparation

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories