繁体   English   中英

如何按 Typescript 中的给定属性对对象数组进行排序?

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

假设您有以下类型的对象数组:

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

你如何在不被类型系统绊倒的情况下按给定的属性排序? 例如:

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

您可以使用Array.prototype.sort

例如:

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

了解有关排序 function 的更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

你可以定义一个 function 像

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

然后可以像这样使用

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

这也适用于对象t => tabc中的嵌套属性,或者适用于需要进一步派生排序键的情况,例如t => tatoLowerCase()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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