How to Sort an Array in JavaScript | The School of Code

Settings

Appearance

Choose a typography theme that suits your style

Back to How-to Guides
JavaScript

How to Sort an Array in JavaScript

Learn how to sort arrays in JavaScript including numbers, strings, and objects.

JavaScriptSortingArrays

JavaScript’s sort() method can sort arrays, but requires care with numbers.

Basic String Sorting

Strings sort alphabetically by default:

const fruits = ["banana", "apple", "cherry"];
fruits.sort();
console.log(fruits); // ["apple", "banana", "cherry"]

Sorting Numbers

Numbers require a compare function:

const numbers = [10, 2, 5, 1, 9];

// Wrong: sorts as strings!
numbers.sort();
console.log(numbers); // [1, 10, 2, 5, 9]

// Correct: ascending
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 5, 9, 10]

// Descending
numbers.sort((a, b) => b - a);
console.log(numbers); // [10, 9, 5, 2, 1]

Sorting Without Modifying Original

Use spread operator or slice:

const original = [3, 1, 2];

// Create sorted copy
const sorted = [...original].sort((a, b) => a - b);

console.log(original); // [3, 1, 2] (unchanged)
console.log(sorted);   // [1, 2, 3]

Sorting Objects

Sort by object properties:

const people = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Charlie", age: 35 }
];

// Sort by age
people.sort((a, b) => a.age - b.age);
console.log(people);

// Sort by name
people.sort((a, b) => a.name.localeCompare(b.name));
console.log(people);

Case-Insensitive String Sorting

const names = ["alice", "Bob", "CHARLIE"];

// Case-insensitive sort
names.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(names); // ["alice", "Bob", "CHARLIE"]

Sorting by Multiple Criteria

const students = [
  { name: "Alice", grade: "A", age: 15 },
  { name: "Bob", grade: "B", age: 12 },
  { name: "Charlie", grade: "A", age: 12 }
];

// Sort by grade, then by age
students.sort((a, b) => {
  if (a.grade !== b.grade) {
    return a.grade.localeCompare(b.grade);
  }
  return a.age - b.age;
});

toSorted() - Non-Mutating Sort (ES2023+)

const numbers = [3, 1, 2];

// Returns new sorted array
const sorted = numbers.toSorted((a, b) => a - b);

console.log(numbers); // [3, 1, 2] (unchanged)
console.log(sorted);  // [1, 2, 3]

Summary

  • Use sort() for strings (sorts in place)
  • Use sort((a, b) => a - b) for numbers
  • Use spread [...arr].sort() to avoid mutation
  • Use localeCompare() for proper string comparison
  • Use toSorted() (ES2023+) for non-mutating sort