3

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

5
  • Have you tried? Which problems did you come across? Commented Sep 27, 2022 at 12:29
  • @GuillaumeBrunerie I've looked over the Array.prototype.sort() docs and came up with the following sort((a,b) => a[property] > b[property] ? 1 : -1). IMO, this is verbose, so I was hoping from something a little slicker. Commented Sep 27, 2022 at 12:43
  • I'm afraid there is no slicker way, not built-in to Javascript at least. Commented Sep 27, 2022 at 12:55
  • 1
    Does this answer your question? Sort an array of objects in typescript? Commented Sep 27, 2022 at 13:28
  • Lots of npm packages are available for this sort of thing. Commented Sep 27, 2022 at 13:29

2 Answers 2

4

You can use Array.prototype.sort

For example:

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

You can define a function like

function sortBy<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: Type[] = sortBy(arr, t => t.a)
const sortedC: Type[] = sortBy(arr, t => t.c)
// or if you need a different comparison
const sortedX = sortBy(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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.