Tips for transforming alphanumeric characters into value ranges using Typescript

myArray = ["AB01","AB02","AB03","AB04","AB11","BC12","BC13", "SB33"];

// code snippet to create expected string: "AB01-AB04, AB11, BC12-BC13, SB33"

The array contains combinations of one or two letter characters followed by two or three digits. Examples include A001, A002, AB001, AC01, B01, etc.

Please note that only these specific formats are considered valid.

Is there a simpler way to achieve the desired output?

Answer №1

let myArray = ["AB01","AB05","ABCDEFG01123","ABCDEFG01124","AB02","AB03","AB04","AB11","BC12","BC13", "SB33"];

function getRanges(array, group) {
  var ranges = [], rstart, rend;
  for (var i = 0; i < array.length; i++) {
    rstart = array[i];
    rend = rstart;
    while (array[i + 1] - array[i] == 1) {
      rend = array[i + 1];
      i++;
    }
    ranges.push(rstart == rend ? group+rstart+'' : group+rstart + '-' + group+rend);
  }
  return ranges;
}

// grouping elements.
let groups = myArray.reduce((groups,item)=>{
  let belongsTo = item.match(/[a-zA-Z]/g).join('');
  groups[belongsTo] ? groups[belongsTo].push(item) :groups[belongsTo]=[item];
  return groups;
},{})

let expectedString = Object.entries(groups).reduce((output,[key,value])=>{
  output=`${output}${output.length ? ', ' : ''}${getRanges(value.map(i=>i.match(/[0-9]/g).join('')),key)}`;
  return output;
},'');

console.log(expectedString);
// expected string "AB01-AB04, AB11, BC12-BC13, SB33"

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

Transforming a single object into several arrays

I have a JSON file called "icon.json" that contains the following data: [ { "name": "happy", "url": "1.gif" }, { "name": "excited", "url": "2.gif" }, { "name": "surprised", "url": "3.gif" ...

OpenTok Angular 6 encountered an error with code TS2314 stating that the generic type 'Promise<T>' needs to have 1 type argument specified

Issue in opentok.d.ts File: Error TS2314 npm version: 6.2.0 node: v8.10.0 Angular CLI: 6.2.3 Operating System: Linux x64 Angular Version: 7.0.0-beta.5 @opentok/client": "^2.14.8 ...

How to efficiently display nested object data using Angular Keyvalue pipe

I am facing an issue with a particular HTTP request that returns an observable object containing multiple properties. One of these properties is the 'weight' object which has two key values, imperial and metric. While attempting to loop through ...

Choose three different images and one corresponding word from a JavaScript array to be displayed individually on the screen in separate div containers

I am in the process of developing a web game that will showcase 3 images on the screen, and the player must select the image that corresponds to the displayed word. I have successfully created a JavaScript array containing the images and words retrieved fr ...

Angular and Jest combo has encountered an issue resolving all parameters for the AppComponent. What could be causing this error?

I am currently working within a Typescript Monorepo and I wish to integrate an Angular 8 frontend along with Jest testing into the Monorepo. However, I am facing some challenges. The tools I am using are: Angular CLI: 8.3.5 My Approach I plan to use ...

Ways to enforce a specific type based on the provided parameter

Scenario Background: // Code snippet to do validation - not the main focus. type Validate<N, S> = [S] extends [N] ? N : never; // Note that by uncommenting below line, a circular constraint will be introduced when used in validateName(). // type Val ...

Wrapping around binary addition of two numbers in C++

Yesterday, I had a question regarding adding two binary numbers which was successfully resolved. The value in C is correct, but now I am struggling with handling wrap-around values. To address this, I created another array S and copied the value of C (ob ...

Leveraging a Derived-Class Object Within the Base-Class to Invoke a Base-Class Function with Derived-Class Information

I have a situation where I need to access a method from a derived class in my base generic component that returns data specific to the derived class. The first issue I encountered is that I am unable to define the method as static in the abstract class! ...

Choosing the initial choice with ngFor: A step-by-step guide

I'm having trouble selecting the first option after the user enters their email, but it remains unselected. Any ideas on how to solve this? view image here HTML Code: <label for="login"><b>User:</b></label> <inpu ...

Error in Typescript for the prop types of a stateless React component

When reviewing my project, I came across the following lines of code that are causing a Typescript error: export const MaskedField = asField(({ fieldState, fieldApi, ...props }) => { const {value} = fieldState; const {setValue, set ...

Creating a randomly generated array within a Reactjs application

Every time a user clicks a button in reactjs, I want to create a random array of a specific size. The code for generating the array looks like this: const generateArray = (arraySize: number): number[] => { return [...Array(arraySize)].map(() => ~~( ...

Ways to verify the functionality of a function utilizing a Subscription that yields no return value

I'm working with a TypeScript ModelService that has an edit function: edit(model: Model): Observable<Model> { const body = JSON.stringify(model); return this.http.put(`/models/edit/${model.id}`, body)); } Additionally, there is a TypeScrip ...

Getting the Class name in Typescript

How can you retrieve the class name from within a Class in typescript? For instance, consider this code snippet: export class SomeRandomName extends AbstractSomething<SomeType> implements OnDestroy { className = 'SomeRandomName'; Is th ...

Does anyone have experience using the useRef hook in React?

Can someone help me with this recurring issue: "Property 'value' does not exist on type 'never'" interface InputProps { name: string; icon?: ReactElement; placeholder?: string; } const Input = ({ name, icon: Icon, ...rest }: Inpu ...

Using Symbol.iterator in Typescript: A step-by-step guide

I have decided to upgrade my old React JavaScript app to React Typescript. While trying to reuse some code that worked perfectly fine in the old app, I encountered errors in TS - this is also my first time using TS. The data type I am exporting is as foll ...

Storing data received from httpClient.get and utilizing it in the future after reading

Searching for a solution to read and store data from a text file, I encountered the issue of variable scope. Despite my attempts to use the data across the project by creating a global variable, it still gets cleared once the variable scope ends. import ...

The data type 'string | number | boolean' cannot be assigned to type 'undefined'. Specifically, the type 'string' is incompatible with type 'undefined'. Error code: ts(2322)

When attempting to create a partial object with specific fields from a full object that meet certain criteria, I encountered a TypeScript error message. To better explain this issue, I designed a test module to showcase the concept/problem without using ac ...

Is There a Comparable Feature to *ngIf in DevExtreme?

Currently, I am diving into the world of webapp development using DevExtreme. As a novice in coding, this is my first time exploring the functionalities of DevExtreme. Essentially, I am seeking guidance on how to display certain elements based on specific ...

Starting a nested JSON structure with TypeScript and Angular 7

I'm encountering an error when attempting to make a POST request by sending an object TypeError: Can not set property 'ItemCode' of undefined My setup involves Angular 7 and Typescript Here is my initial JSON: objEnvio:any = <an ...

Initiating a GET request to execute an SQL query with specified parameters

Let me provide some background information. I am currently using Angular for the frontend and Express for the backend, while also learning how to effectively utilize both technologies. In my application, there is a parent component that generates a group ...