简体   繁体   中英

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

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

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

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 => tabc or for cases where you need to derive the sort key further eg t => tatoLowerCase()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM