Sort By
EasyUpdated: Oct 13, 2025
Practice on:
Problem
Given an array arr and a function fn, return a sorted array sortedArr.
You can assume fn only returns numbers and those numbers determine the sort order of sortedArr. sortedArr must be sorted in ascending order by
fn output.
You may assume that fn will never duplicate numbers for a given array.
Examples
Example 1
Input: arr = [5, 4, 1, 2, 3], fn = (x) => x
Output: [1, 2, 3, 4, 5]
Explanation: fn simply returns the number passed to it so the array is sorted in ascending order.
Example 2
Input: arr = [{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x
Output: [{"x": -1}, {"x": 0}, {"x": 1}]
Explanation: fn returns the value for the "x" key. So the array is sorted based on that value.
Example 3
Input: arr = [[3, 4], [5, 2], [10, 1]], fn = (x) => x[1]
Output: [[10, 1], [5, 2], [3, 4]]
Explanation: arr is sorted in ascending order by number at index=1.
Constraints
arris a valid JSON arrayfnis a function that returns a number1 <= arr.length <= 5 * 10^5
Solution
Method 1 - Using Array.sort() with Custom Comparator
Intuition
Use JavaScript's built-in sort() method with a custom comparator function that applies the given function fn to each element and compares the results.
Approach
- Use the
sort()method with a comparator function - For each pair of elements, apply the function
fnto get their sort keys - Compare the sort keys to determine the order
- Return the sorted array
Code
JavaScript
/**
* @param {Array} arr
* @param {Function} fn
* @return {Array}
*/
var sortBy = function(arr, fn) {
return arr.sort((a, b) => fn(a) - fn(b));
};
TypeScript
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type Fn = (value: JSONValue) => number;
function sortBy(arr: JSONValue[], fn: Fn): JSONValue[] {
return arr.sort((a, b) => fn(a) - fn(b));
}
For completeness, here are equivalent implementations in other languages:
C++
#include <vector>
#include <algorithm>
#include <functional>
template<typename T>
std::vector<T> sortBy(std::vector<T> arr, std::function<int(T)> fn) {
std::sort(arr.begin(), arr.end(), [&fn](const T& a, const T& b) {
return fn(a) < fn(b);
});
return arr;
}
// Example usage with different types
#include <iostream>
#include <string>
int main() {
// Example 1: Sort numbers by their value
std::vector<int> nums = {5, 4, 1, 2, 3};
auto sortedNums = sortBy<int>(nums, [](int x) { return x; });
// Example 2: Sort strings by their length
std::vector<std::string> words = {"hello", "hi", "world"};
auto sortedWords = sortBy<std::string>(words, [](const std::string& s) {
return (int)s.length();
});
return 0;
}
Go
import (
"sort"
)
func sortBy[T any](arr []T, fn func(T) int) []T {
result := make([]T, len(arr))
copy(result, arr)
sort.Slice(result, func(i, j int) bool {
return fn(result[i]) < fn(result[j])
})
return result
}
// Example usage
func main() {
// Sort integers by their value
nums := []int{5, 4, 1, 2, 3}
sortedNums := sortBy(nums, func(x int) int { return x })
// Sort strings by their length
words := []string{"hello", "hi", "world"}
sortedWords := sortBy(words, func(s string) int { return len(s) })
}
Java
import java.util.*;
import java.util.function.Function;
public class Solution {
public static <T> List<T> sortBy(List<T> arr, Function<T, Integer> fn) {
List<T> result = new ArrayList<>(arr);
result.sort(Comparator.comparing(fn));
return result;
}
// Example usage
public static void main(String[] args) {
// Sort integers by their value
List<Integer> nums = Arrays.asList(5, 4, 1, 2, 3);
List<Integer> sortedNums = sortBy(nums, x -> x);
// Sort strings by their length
List<String> words = Arrays.asList("hello", "hi", "world");
List<String> sortedWords = sortBy(words, String::length);
}
}
Kotlin
fun <T> sortBy(arr: List<T>, fn: (T) -> Int): List<T> {
return arr.sortedBy { fn(it) }
}
// Example usage
fun main() {
// Sort integers by their value
val nums = listOf(5, 4, 1, 2, 3)
val sortedNums = sortBy(nums) { it }
// Sort strings by their length
val words = listOf("hello", "hi", "world")
val sortedWords = sortBy(words) { it.length }
}
Python
def sort_by(arr, fn):
"""
Sort array by applying function fn to each element.
Args:
arr: List of elements to sort
fn: Function that takes an element and returns a number for sorting
Returns:
Sorted list in ascending order by fn output
"""
return sorted(arr, key=fn)
# Example usage
if __name__ == "__main__":
# Sort numbers by their value
nums = [5, 4, 1, 2, 3]
sorted_nums = sort_by(nums, lambda x: x)
# Sort dictionaries by 'x' key
dicts = [{"x": 1}, {"x": 0}, {"x": -1}]
sorted_dicts = sort_by(dicts, lambda d: d["x"])
# Sort arrays by second element
arrays = [[3, 4], [5, 2], [10, 1]]
sorted_arrays = sort_by(arrays, lambda x: x[1])
Rust
fn sort_by<T, F>(mut arr: Vec<T>, f: F) -> Vec<T>
where
F: Fn(&T) -> i32,
{
arr.sort_by_key(|x| f(x));
arr
}
// Alternative that doesn't mutate original
fn sort_by_immutable<T, F>(arr: Vec<T>, f: F) -> Vec<T>
where
T: Clone,
F: Fn(&T) -> i32,
{
let mut result = arr.clone();
result.sort_by_key(|x| f(x));
result
}
// Example usage
fn main() {
// Sort numbers by their value
let nums = vec![5, 4, 1, 2, 3];
let sorted_nums = sort_by(nums, |&x| x);
// Sort strings by their length
let words = vec!["hello".to_string(), "hi".to_string(), "world".to_string()];
let sorted_words = sort_by(words, |s| s.len() as i32);
}
Complexity
- ⏰ Time complexity:
O(n log n)where n is the length of the array (due to the sorting operation) - 🧺 Space complexity:
O(1)for in-place sorting, orO(n)if creating a new array