Zest.

JavaScript: Sort an array

A short, tested JavaScript example for sort an array. Copy it and adjust the names and paths for your project.

JavaScript
nums.sort((a, b) => a - b);                    // ascending numbers
words.sort((a, b) => a.localeCompare(b));      // strings
people.sort((a, b) => b.age - a.age);          // by field, descending

const sorted = [...nums].sort((a, b) => a - b); // without mutating

Find it in Zest

Search for “javascript sort an array” in Zest and this example appears above the results, with other matches to choose from. Searches stay private.

More JavaScript examples

All JavaScript examples