Home > OS >  How do you sort an array of objects by a given property in Typescript?
How do you sort an array of objects by a given property in Typescript?

Time:09-27

Say you have an array of objects of the following type:

type Obj = {
  id: number,
  created: Date, 
  title: string
}

How would you sort by a given property without tripping up over the type system? For example:

const numberSorted = objArray.sortBy("id");
const dateSorted = objArray.sortBy("created");
const stringSorted = objArray.sortBy("title");

CodePudding user response:

You can use Array.prototype.sort

For example:

objArray.sort((a, b) => {
    // Some code for comparison
});

Learn more about sort function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

CodePudding user response:

You can define a function like

function sortByProperty<T, V>(
        array: T[],
        valueExtractor: (t: T) => V,
        comparator?: (a: V, b: V) => number) {

  // note: this is a flawed default, there should be a case for equality
  // which should result in 0 for example
  const c = comparator ?? ((a, b) => a > b ? 1 : -1) 
  return array.sort((a, b) => c(valueExtractor(a), valueExtractor(b)))
}

which then could be used like

interface Type { a: string, b: number, c: Date }
const arr: Type[] = [
  { a: '1', b: 1, c: new Date(3) },
  { a: '3', b: 2, c: new Date(2) },
  { a: '2', b: 3, c: new Date(1) },
]
const sortedA: T[] = sortByProperty(arr, t => t.a)
const sortedC: T[] = sortByProperty(arr, t => t.c)
// or if you need a different comparison
const sortedX: T[] = sortByProperty(arr, t => t.c, (a, b) => a.getDay() - b.getDay())

This also works with nested properties within objects t => t.a.b.c or for cases where you need to derive the sort key further e.g. t => t.a.toLowerCase()

  • Related