Sort by Length with Comparator
Write a JavaScript function that sorts an array of strings by their length in ascending order using Array.sort() with a custom comparator function. The comparator should compare the length property of each string to determine the sort order.
Array.sort() in JavaScript accepts an optional comparator function that defines the sort order. The comparator receives two elements (a, b) and returns a negative number if a should come before b, a positive number if b should come before a, or zero if they are equal. For sorting by length, use a.length - b.length which returns a negative number when a is shorter.
JavaScript's sort is an in-place algorithm that mutates the original array. To avoid mutation, create a copy with slice() before sorting. The default sort converts elements to strings and compares their UTF-16 code units, which is rarely what you want for non-string data. Providing a custom comparator gives you full control over the sort logic.
Time complexity is O(n log n) where n is the array length, as sort uses a comparison-based algorithm (typically Timsort in V8). Space complexity is O(n) for the sorted copy. The comparator is called O(n log n) times during the sort.
Edge cases include empty arrays, single-element arrays, strings of equal length (comparator returns 0 which preserves original order for stable sort), and arrays where all strings have different lengths.
Example Input & Output
Same length, stable sort
Single element
Already in order
Already sorted by length
Sorted by length ascending
Algorithm Flow

Solution Approach
Sort an array of strings by their character length using sort() with a custom comparator that compares length properties.
The comparator sorts in ascending order of length. For descending, use b.length - a.length. Strings with equal length maintain their relative order for stable sort implementations.
Time O(n log n), Space O(1).
Best Answers
function solution(words) {
return words.slice().sort(function(a, b) {
return a.length - b.length;
});
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
