Angular: Sorting Arrays

Here’s a simple technique for sorting an array of objects.

It accepts a simple function that returns a 1 or -1 result.

// The questions property is an array of objects with a display order property.
// We want them to be ordered ascending.
// NOTE: The sort method returns the sorted array.
let ql = this.questions.sort((a, b) => (a.displayOrder < b.displayOrder) ? -1 : 1);

This will sort descending:

// The questions property is an array of objects with a display order property.
// We want them to be ordered descending.
// NOTE: The sort method returns the sorted array.
let ql = this.questions.sort((a, b) => (a.displayOrder > b.displayOrder) ? -1 : 1);


Revision #2
Created 21 February 2025 08:24:30 by glwhite
Updated 21 February 2025 08:26:33 by glwhite