@FahadM to JavaScriptEnglish • 9 days ago

How do you sort an array of JavaScript objects alphabetically by a string property?

message-square
0
2
How do you sort an array of JavaScript objects alphabetically by a string property?
@FahadM to JavaScriptEnglish • 9 days ago

Sorting an array of JavaScript objects alphabetically by a string property using .toSorted() with .localeCompare() orders items naturally by text while returning a new array without changing your original data. Passing { sensitivity: “base” } keeps sorting smooth even when letter casing is mixed.

Steps to Sort Objects by a String Property

  • Select the string field: Access the property you want to sort by, such as item.name or item.title.

  • Use .localeCompare(): Compare strings according to natural alphabetical rules and ignore case differences with { sensitivity: “base” }.

  • Keep original data safe: .toSorted() creates a sorted copy without mutating the original array.

Example: Sorting Students Alphabetically by Name

JavaScript
const students = [
  { id: 1, name: "Zara" },
  { id: 2, name: "ali" },
  { id: 3, name: "Bilal" },
  { id: 4, name: "Ayesha" }
];

const sortedStudents = students.toSorted((a, b) =>
  a.name.localeCompare(b.name, undefined, { sensitivity: "base" })
);

console.log(sortedStudents);
// [
//   { id: 2, name: "ali" },
//   { id: 4, name: "Ayesha" },
//   { id: 3, name: "Bilal" },
//   { id: 1, name: "Zara" }
// ]