Published: December 16 2022

JavaScript - Sort an Array of Objects by Property in Vanilla JS

This is a super quick post to show how to sort an array of objects by property value in JavaScript (or TypeScript).

JavaScript SortBy Function

This custom JavaScript sortBy() function sorts an array of items by the specified prop, sort order is controlled by the desc parameter. The parse function param parses each value when sorting to enable case insensitive sorting and sorting by date.

Internally the function uses the JavaScript Array sort() function which accepts a callback that compares all the items in the array and sorts them. The compare function returns a number (1, -1 or 0) to determine which way to sort each pair of items (a and b).

function sortBy({ items, prop, desc = false, parse = x => x }) {
    const sortOrder = desc ? -1 : 1;
    return items.sort((a, b) => {
        // sort comparison function
        let result = 0;
        if (parse(a[prop]) < parse(b[prop])) {
            result = -1;
        }
        if (parse(a[prop]) > parse(b[prop])) {
            result = 1;
        }
        return result * sortOrder;
    });
}


SortBy Function Usage

Here's a few examples of how to use the sortBy() function:

// sample array of objects
const items = [
    {
        "id": 1,
        "firstName": "Test",
        "lastName": "User",
        "age": 30,
        "company": "TESTCO",
        "dob": "1992-02-01"
    },
    {},
    {},

...

];

// sort items by id desc
sortBy({ items, prop: 'id', desc: true });

// sort by first name
sortBy({ items, prop: 'firstName' });

// sort by first name (case insensitive)
sortBy({ items, prop: 'firstName', parse: x => x.toLowerCase() });

// sort by DOB
sortBy({ items, prop: 'dob', parse: x => new Date(x) });


Real World Example in Angular

I used a similar approach in an Angular tutorial recently to enable sorting data in a table. For the full tutorial including a live demo see Angular 14 - Paging and Sorting Table Data Example & Tutorial.

It's slightly different because it's in a class component and stores the current sort property and order in the class, here's the app component with the sortBy() method:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({ selector: 'app-root', templateUrl: './app.component.html' })
export class AppComponent {
    items: any[] = [];
    pageOfItems?: Array<any>;
    sortProperty: string = 'id';
    sortOrder = 1;
    loading = false;

    constructor(private http: HttpClient) { }

    ngOnInit() {
        // fetch items from the backend api
        this.loading = true;
        this.http.get<any[]>('/items')
            .subscribe(x => {
                this.items = x;
                this.loading = false;
            });
    }

    onChangePage(pageOfItems: Array<any>) {
        // update current page of items
        this.pageOfItems = pageOfItems;
    }

    sortBy(property: string) {
        this.sortOrder = property === this.sortProperty ? (this.sortOrder * -1) : 1;
        this.sortProperty = property;
        this.items = [...this.items.sort((a: any, b: any) => {
            // sort comparison function
            let result = 0;
            if (a[property] < b[property]) {
                result = -1;
            }
            if (a[property] > b[property]) {
                result = 1;
            }
            return result * this.sortOrder;
        })];
    }

    sortIcon(property: string) {
        if (property === this.sortProperty) {
            return this.sortOrder === 1 ? '☝️' : '👇';
        }
        return '';
    }
}

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some Vanilla JS Help?

Search fiverr to find help quickly from experienced Vanilla JS developers.



Supported by