Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Sort by Name

Rendering Listsmedium

Course · Section 11: Working With Arrays · Lecture 157: The map Method

Implement `sortByName(items)` returning a new array sorted ascending by `name`, without mutating the input.

Sample tests

Input: sortByName([{"name":"b"},{"name":"a"}])
Output: [{"name":"a"},{"name":"b"}]
Input: sortByName([])
Output: []

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • items.sort(...) mutates the prop or state array, a classic React bug.
  • Comparing strings with subtraction, which only works for numbers.

Learning resources

  • React: Rendering Lists
Approach & explanation (try first)

Spread into a new array first because sort mutates. localeCompare gives correct alphabetical order, and the original list is preserved.

Loading...
⌘/Ctrl + Enter

Run your code to see results.