Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting by specific values in Typescript

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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, nextWord) => {
  const test = value => {
    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
}
))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading