Sort Array of Objects by String Property Value

Sort Array of Objects by String Property Value

Introduction

Objects are used to store a set of properties, each of which may be thought of as a relationship between a name (or key) and a value - thus, objects are a collection of key-value pairs.

In this guide, we'll take a look at how to sort an Array of Objects by a string property's value using the sort() method.

Sorting data is one of the core usages of software! We can sort and filter data on various conditions, and sorting by the value of a string property is a common one. For example, suppose we have a list of students with their firstName and lastName:

const students = [
    { firstName: "John", lastName: "Doe", graduationYear: 2022 },
    { firstName: "Stephen", lastName: "Matt", graduationYear: 2023 },
    { firstName: "Abigail", lastName: "Susu", graduationYear: 2022 },
    { firstName: "Zara", lastName: "Kate", graduationYear: 2024 },
    { firstName: "Daniel", lastName: "Vic", graduationYear: 2023 }
];

We could sort these students by either their firstName or lastName. We could write custom comparators (such as to compare lenghts), sort them lexicographically, sort by inclusion of a substring, etc.

Sort List of Objects by String

JavaScript lists implement a sort() method, which additionally accepts a callback function that lets you implement a custom comparator. By default, the sort() method logically sorts the given data type. For integers, comparison is fairly straightforward (in ascending order), and strings are sorted lexicographically:

const names = ["john", "kate", "dan"];
// Sorting array of strings, lexicographically
console.log(names.sort()); // ["dan","john","kate"]

Since we want to sort an array of objects, based on an underlying property, we'll want to define a custom callback function for sorting. The callback function accepts two parameters - two elements to be compared at any given time. Based on the comparison, you'll return -1, 0 or 1, denoting the result of the comparison. If -1 is returned, a is considered lesser than b. 0 signifies equality. 1 signifies that b is greater than a:

let sortedStudents = students.sort((a, b) => {
    if (a.firstName < b.firstName) {
        return -1;
    }
    if (a.firstName > b.firstName) {
        return 1;
    }
    return 0;
});

console.log(sortedStudents);

Note: We can compress the if statements by not using the curly braces.

This would output:

[
    { firstName: "Abigail", lastName: "Susu", graduationYear: 2022 },
    { firstName: "Daniel", lastName: "Vic", graduationYear: 2023 },
    { firstName: "John", lastName: "Doe", graduationYear: 2022 },
    { firstName: "Stephen", lastName: "Matt", graduationYear: 2023 },
    { firstName: "Zara", lastName: "Kate", graduationYear: 2024 }
];

Note: When comparing strings, upper case letters have a different weight than lower case letters and A would be, for instance, positioned after b. It's generally considered good practice to equalize the strings to either all lowercase or all uppercase (more commonly, lowercase, due to efficiency).

Let's account for the case, and shorten/compact the if statements using a null coalescing operator:

let sortedStudents = students.sort((a,b) => (a.firstName.toLowerCase() < b.firstName.toLowerCase()) ? -1 : ((b.firstName.toLowerCase() > a.firstName.toLowerCase()) ? 1 : 0));

console.log(sortedStudents);

This results in:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

const students = [
    { firstName: "John", lastName: "Doe", graduationYear: "2021" },
    { firstName: "Stephen", lastName: "Matt", graduationYear: "2026" },
    { firstName: "Abigail", lastName: "Susu", graduationYear: "2022" },
    { firstName: "Zara", lastName: "Kate", graduationYear: "2024" },
    { firstName: "Daniel", lastName: "Vic", graduationYear: "2023" }
];

Even though the years are strings here, we can easily sort them as well:

let sortedStudents = students.sort((a,b) => (a.graduationYear < b.graduationYear) ? -1 : ((b.graduationYear > a.graduationYear) ? 1 : 0))

console.log(sortedStudents);

This results in:

[
    { firstName: "John", lastName: "Doe", graduationYear: "2021" },
    { firstName: "Abigail", lastName: "Susu", graduationYear: "2022" },
    { firstName: "Daniel", lastName: "Vic", graduationYear: "2023" },
    { firstName: "Zara", lastName: "Kate", graduationYear: "2024" },
    { firstName: "Stephen", lastName: "Matt", graduationYear: "2026" }
];

Conclusion

In this short article - we took a look at sorting an array of objects based on a string property, using the sort() method in JavaScript.

Last Updated: March 21st, 2022
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

Go Unlimited

  • Access all of our courses and guided projects
  • Master new skills and advance your career
  • Comprehensive lessons and expert guidance
  • Early access to all new courses and content

Sign up today!

$19/mo

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms