Sort Array Alphabetically

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to sort an array of objects alphabetically based on a given property using JavaScript. We will use the Array.prototype.sort() method and the String.prototype.localeCompare() method to compare the values for the given property. This will allow us to easily sort the array in ascending or descending order, based on our requirements.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28618{{"`Sort Array Alphabetically`"}} javascript/data_types -.-> lab-28618{{"`Sort Array Alphabetically`"}} javascript/arith_ops -.-> lab-28618{{"`Sort Array Alphabetically`"}} javascript/comp_ops -.-> lab-28618{{"`Sort Array Alphabetically`"}} end

How to Sort an Array Alphabetically Based on a Given Property in JavaScript

To sort an array of objects alphabetically based on a given property in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.sort() to sort the array based on the given property.
  3. Use String.prototype.localeCompare() to compare the values for the given property.

Here's an example code snippet that you can use:

const alphabetical = (arr, getter, order = "asc") =>
  arr.sort(
    order === "desc"
      ? (a, b) => getter(b).localeCompare(getter(a))
      : (a, b) => getter(a).localeCompare(getter(b))
  );

You can call the alphabetical function with an array of objects and the getter function that returns the property to sort by. Here's an example usage:

const people = [{ name: "John" }, { name: "Adam" }, { name: "Mary" }];
alphabetical(people, (g) => g.name);
// [ { name: 'Adam' }, { name: 'John' }, { name: 'Mary' } ]
alphabetical(people, (g) => g.name, "desc");
// [ { name: 'Mary' }, { name: 'John' }, { name: 'Adam' } ]

Summary

Congratulations! You have completed the Sort Array Alphabetically lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like