2724. Sort By

 

Sorting Made Easy with a Custom sortBy Function in JavaScript

Sorting arrays is a fundamental task in programming, and JavaScript provides powerful methods to accomplish this. However, there are times when you need to sort based on custom criteria. Let's dive into creating a custom sortBy function that allows for flexible and efficient sorting based on any criteria you define.

Problem Statement

We need a function sortBy that sorts an array based on a provided function. This function will take two arguments:

  1. arr (Array): The array to be sorted.

  2. fn (Function): The callback function that defines the sorting criterion.

Code Implementation

Here is the implementation of our custom sortBy function:

javascript
/**
 * @param {any[]} arr
 * @param {Function} fn
 * @return {any[]}
 */
var sortBy = function(arr, fn) {
    return arr.sort((a, b) => fn(a) - fn(b));
};

// Example Usage:
// Sorting an array of numbers based on their values
let numbers = [3, 1, 4, 1, 5, 9];
let sortedNumbers = sortBy(numbers, x => x);
console.log(sortedNumbers); // Output: [1, 1, 3, 4, 5, 9]

// Sorting an array of objects based on a property
let people = [
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 30 },
    { name: 'Charlie', age: 20 }
];
let sortedByAge = sortBy(people, person => person.age);
console.log(sortedByAge);
// Output: [
//   { name: 'Charlie', age: 20 },
//   { name: 'Alice', age: 25 },
//   { name: 'Bob', age: 30 }
// ]

Intuition

The intuition behind this sortBy function is to provide a versatile and reusable way to sort arrays according to any given criterion. By passing a callback function fn to define the sorting logic, we make our function adaptable to various use cases, whether we're sorting numbers, strings, or objects.

Approach

  1. Function Definition: Define the sortBy function to accept an array and a callback function.

  2. Sorting Logic: Use the built-in sort method of JavaScript arrays. The sort method requires a comparator function to determine the order of elements.

  3. Comparator Function: The comparator function (a, b) => fn(a) - fn(b) uses the result of the callback function fn to sort the array elements. If fn(a) is less than fn(b), a will be placed before b.

Complexity Analysis

  • Time Complexity: The sort method generally has a time complexity of O(n log n), where n is the number of elements in the array. This is due to the efficient sorting algorithms implemented under the hood in JavaScript.

  • Space Complexity: The space complexity is typically O(1) for in-place sorting. However, some implementations may use additional space for temporary variables during sorting operations.

Example Cases

  • Sorting Numbers: Sort an array of numbers in ascending order.

    javascript
    sortBy([3, 1, 4, 1, 5, 9], x => x); // Output: [1, 1, 3, 4, 5, 9]
    
  • Sorting Objects: Sort an array of objects based on a specific property, such as age.

    javascript
    sortBy([{name: 'Alice', age: 25}, {name: 'Bob', age: 30}, {name: 'Charlie', age: 20}], person => person.age);
    // Output: [{name: 'Charlie', age: 20}, {name: 'Alice', age: 25}, {name: 'Bob', age: 30}]
    

Conclusion

The custom sortBy function provides a flexible and efficient way to sort arrays based on custom criteria. By leveraging the power of JavaScript’s built-in sort method and the flexibility of callback functions, you can sort arrays of numbers, strings, objects, and more with ease.

For more tips, tricks, and coding solutions, check out my LeetCode Solution and stay tuned for more insights on JavaScript and web development!

Happy coding! šŸš€

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic šŸš€ leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

14. Longest Common Prefix