Skip to main content

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);