Home > Mobile >  Sorting by specific values in Typescript
Sorting by specific values in Typescript

Time:05-05

Newbie to Typescript here. I previously coded mostly in scala. Is there a way to sort by specific values in typescript? This is what I might do in scala previously:

Seq("bbb", "foo", "bar", "aaa", "hello", "world", "ccc").sortBy { word =>
  word match {
    case "hello" => 0
    case "bar" => 1
    case "foo" => 2
    case "world" => 3
    case _ => 4
  }
} // val res1: Seq[String] = List(hello, bar, foo, world, bbb, aaa, ccc)

CodePudding user response:

The typescript is responsible for types and not for sorting, in this case, the solution can be found in the js area

console.log(
["bbb", "foo", "bar", "aaa", "hello", "world","ccc"].sort((word: string, nextWord: string) => {
  const test = (value: string):number => {
    switch (value){
      case "hello" : return 0;
      case "bar" : return 1;
      case "foo" : return 2;
      case "world" : return 3
      default : return Infinity; 
    }}
  if (test(word) < test(nextWord)) return -1
  if (test(word) > test(nextWord)) return 1
  return 0
}
))

  • Related