Code Logo

Sort by Length with Comparator

Published at25 Jul 2026
JavaScript Data Structures Medium 0 views
Like0

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

Example 1
Input
["same","size","sort"]
Output
["same","size","sort"]
Explanation

Same length, stable sort

Example 2
Input
["a"]
Output
["a"]
Explanation

Single element

Example 3
Input
["longest","long","short"]
Output
["long","short","longest"]
Explanation

Already in order

Example 4
Input
["z","yy","xxx"]
Output
["z","yy","xxx"]
Explanation

Already sorted by length

Example 5
Input
["cat","a","elephant","dog","be"]
Output
["a","be","cat","dog","elephant"]
Explanation

Sorted by length ascending

Algorithm Flow

Recommendation Algorithm Flow for Sort by Length with Comparator
Recommendation Algorithm Flow for Sort by Length with Comparator

Solution Approach

Sort an array of strings by their character length using sort() with a custom comparator that compares length properties.

function solution(arr) { return arr.sort(function(a, b) { return a.length - b.length; }); }

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

javascript - Approach 1
function solution(words) {
  return words.slice().sort(function(a, b) {
    return a.length - b.length;
  });
}