Sort array
Always make a copy of the array to be sorted. Otherwise, the original array is also sorted. Array is passed by reference even if you assign it to a brand new variable name. It means that both variables point to the same array in memory. If you change one, the other will also change.
To avoid this, you can use structuredClone()
to create a deep copy of the array.
Don't use Array.from()
or slice()
to create a copy of the array, because they only create a shallow copy.
Sort array by 1 property
Code: sort-array-by-00-1-property.mjs
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 orderconsole.log({cars, carsSortedByModel});
Sort array by 2 properties
Code: sort-array-by-01-mutli-properties.mjs
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});