簡體   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