Arranging data based on particular criteria in Typescript

I'm new to Typescript and coming from a background mostly in scala. I'm wondering if there is a way to sort by specific values in Typescript, similar to how I would do it in scala:

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)

Answer №1

In this scenario, the typescript focuses on defining types rather than sorting functions. The solution for sorting can be implemented in the JavaScript section below:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the rationale behind TypeScript permitting undefined methods?

Currently, I am working on a presentation for my development team about TypeScript. I want to demonstrate the importance of type checking through examples, but I'm stumped as to why this particular piece of code is not throwing a compile-time error wh ...

Using Bazel, Angular, and SocketIO Version 3 seems to be triggering an error: Uncaught TypeError - XMLHttpRequest is not recognized

Looking to integrate socket.io-client (v3) into my Angular project using Bazel for building and running. Encountering an error in the browser console with the ts_devserver: ERROR Error: Uncaught (in promise): TypeError: XMLHttpRequest is not a constructor ...

What is the method for converting a JSON string into an [object][object] format using Angular 6?

Is there a way to transform the data shown below into the [[object][object]] structure using Angular 6? resultArray = [{Q_id: "5bbee2fbbb34b98be0464c73", opt_id: 111},{Q_id: "5bbee2fbbb34b98be0464c73", opt_id: 113}] ...

Remove duplicate identifiers from a list containing multiple arrays

How can I remove duplicate assets from the list? Please refer to the image for clarification. I attempted to use map and filter functions, but encountered an issue where additional attributes were lost. The desired outcome is to maintain the structure whi ...

The properties required for type 'never[]' are not present

The type 'never[]' does not have the necessary properties from type '{ login: string; id: number; node_id: string; avatar_url: string; url: string; }': login, id, node_id, avatar_url, url When working on a component that takes an ApiUr ...

Utilizing Material UI and TypeScript to effectively pass custom properties to styled components

Currently, I am utilizing TypeScript(v4.2.3) along with Material UI(v4.11.3), and my objective is to pass custom props to the styled component. import React from 'react'; import { IconButton, styled, } from '@material-ui/core'; con ...

If the Angular Interpolation Binding format is other than "yyyy-MM-dd", the date will not be displayed

I am facing an issue with my interpolation binding when the date format is not 'yyyy-MM-dd' .html: <div class="form-group"> <label>DOB <input type="date" class="form-control" id="birth_date" value={{stu.result.birth_date}}& ...

Components in Angular 4 that are loaded dynamically using attribute directives are enclosed within a <div> element

My goal is to dynamically generate components based on the configuration options, specifically creating a toolbar with different "toolbar items". Following the Angular guide at: https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html, I h ...

Why does my ngFor consistently refresh while the array remains unchanged?

Issue at hand: Whenever I launch this component, the ngFor div continuously updates and causes my RAM to deplete. Typically, ngFor is triggered when the array is updated; however, in my case, the array (announcements) only updates once in the constructor. ...

Found inconsistent results when running a npm script globally versus inline

After running some tests, I discovered that tslint is functioning correctly when using the following command: tslint -c tslint.json --project tsconfig.json 'src/**/*.ts' However, when attempting to integrate it into an npm script, it appears th ...

I'm having trouble with my TypeScript type declaration file not functioning properly

After trying to publish my first TypeScript NPM package and encountering issues with type recognition in my Node.js project, I realized that the type files for my package were not functioning properly. While my project structure includes files like "easyer ...

Halt of dispatcher playback occurs after a duration of 10 minutes with discord.js

Currently, I've been working on a music bot using discord.js. To handle audio streaming, I'm utilizing @discordjs/opus and ytdl-core-discord. Everything runs smoothly when testing the bot locally on my machine - songs from YouTube are played with ...

Struggling to narrow down the type of an object property even after verifying it with a type guard

Flavor is a distinct union, represented as a value of an Object. While attempting to execute this idea, it functions in js, however, TypeScript does not approve. ts playground link Desired Outcome: For TypeScript to comprehend discriminated unions within ...

Prioritize the timepicker over the use of a modal window

Having an issue with my time picker in Angular being blocked by a modal window. Component.ts open() { const amazingTimePicker = this.atp.open(); amazingTimePicker.afterClose().subscribe(time => { console.log(time); }); } // T ...

Lazy-loading modules in SSR Angular 8 applications are currently unspecified

I am currently in the process of setting up my Angular 8 application to work with server-side rendering (SSR). However, I am encountering some undefined errors in webpack when running my application using ng serve, especially with lazy-loaded modules. Ever ...

What is the best approach to manage the package versions of react, react-dom, @types/react, and @types/react-dom?

Recently, I decided to update the versions of react/react-dom in my project from 16.3.2 to 16.8.6 so that I could start using hooks. Surprisingly, after making some minor adjustments to my code, the update went smoothly. However, since we are utilizing ty ...

How can I retrieve the date from the following week with Ionic?

I am looking to retrieve the date of today plus 7 days. Currently, I am retrieving today's date using the following code: public dateToday: string = new Date().toLocaleDateString('de-DE'); After searching on Google, I came across the soluti ...

Using Typescript file for importing configurations instead of relying on json files dynamically

Let me give you some context: Our team is working on creating AWS CDK modules using Typescript (just so you know, I'm not very experienced in TS). One of the modules we're developing is for managing container-based applications that developers c ...

Using InjectionToken results in the generation of the error message "Encountered an issue while resolving symbol values

Recently, I encountered an issue while building my Ionic 3 app using ionic cordova build ios --prod. Everything was functioning perfectly until a package update caused some complications, preventing me from successfully building the app. I suspect that t ...

Converting JSON array to custom object array in TypeScript

As a newcomer to this area, please excuse any inaccuracies in my language. Don't hesitate to ask for more details if needed. I currently have some TypeScript interfaces: export interface Item { id: string type: string state: string } ex ...