Search⌘ K

Tip 9: Avoid Sort Confusion with the Spread Operator

Explore how to manage array sorting in JavaScript without causing data mutation. Understand how using the spread operator to copy arrays before sorting ensures consistent and reliable data handling, especially in applications with sortable tables.

Sorting tabular data

You’ve seen by now that you can replace many mutating functions with the spread operator. What should you do when there’s a function that you can’t easily replace? The answer is fairly simple: Use the spread operator to create a copy of the original array, and then mutate that one.

Don’t let the simplicity of the answer fool you. Mutation bugs can sneak up when you least expect them.

This comes up in applications that have tabular sorting data. If you haven’t written an application that displays tabular data, wait around—I guarantee you’ll do it. And the minute you create that table of tabular data, the next request you’ll hear ...