Sort array by

Overview

Always make a copy of the array to be sorted. Otherwise, the original array is also sorted. Arrays are passed by reference which means that when you make one array equal to another it will change both whenever you make an edit to one.

Sort array by 1 property

const cars = [
    {model: "Honda" , "year": 1999}, 
    {model: "Toyota", "year": 2018}, 
    {model: "Toyota", "year": 2021}, 
    {model: "Honda" , "year": 2011}, 
    {model: "Bez"   , "year": 1926}  
]


const carsSortedByModel = structuredClone(cars);                // Deep copy.
carsSortedByModel.sort((a, b) => (a.model > b.model) ? 1 : -1); // Ascending order

console.log({cars, carsSortedByModel});

Sort array by 2 properties

const cars = [
    {model: "Honda" , "year": 1999}, 
    {model: "Toyota", "year": 2018}, 
    {model: "Toyota", "year": 2021}, 
    {model: "Honda" , "year": 2011}, 
    {model: "Bez"   , "year": 1926}  
]

// Sort model Ascending.
function compareByModel(a, b){
    if(a.model > b.model) {
        return 1;
    } else {
        return -1
    }
}

// Sort model Ascending and then Year Descending.
function compareByModelAndYear(a, b){
    if(a.model > b.model) return 1;
    if(a.model < b.model) return -1;

    if(a.year > b.year) return -1;
    if(a.year < b.year) return 1;
    return 0;
}

const carsSortedByModel = structuredClone(cars);    // Deep copy.
carsSortedByModel.sort(compareByModelAndYear);

console.log({cars, carsSortedByModel});