JS Built-ins
← Array195 / 226
ArrayArray.prototype.toSortedintermediate

Sort by String Length

πŸ“– Usage Example
const nums = [5, 2, 8, 1]
nums.toSorted((a, b) => b - a)  // β†’ [8, 5, 2, 1]

Pass a comparator to toSorted() to control the sort order without mutating the original.

Array.prototype.toSorted β€” Custom Comparator

You can pass any comparator function to toSorted, just like sort.

Implement sortByLength which returns a copy of the string array sorted by string length (shortest first).

πŸ’‘ Hints (2)
  • β€’ Use (a, b) => a.length - b.length as the comparator
  • β€’ toSorted with a comparator works identically to sort with one, but returns a copy