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

Apply criteria to an array based on multiple attribute conditions

Given an array containing parent-child relationships and their corresponding expenses, the task is to filter the list based on parents that have a mix of positive and negative expenses across their children. Parents with only positive or negative child exp ...

When conducting a test, it was found that the JSX element labeled as 'AddIcon' does not possess any construct or call signatures

Here is a code snippet I'm currently working with: const tableIcons: Icons = { Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), Check: forwardRef((props, ref) => <Check {...props} ref={ref} />) }; const AddIcon ...

Error: The function was expecting a mapDiv with the type of Element, but instead undefined was passed - google

I have a map within a div tagged with #mapa. Whenever I try to plot a route on the map, it refreshes. I don't want the map to refresh, and here is the code I currently have: <div style="height: 500px; width: auto;" #mapa> <google-map heigh ...

Navigating Routes with Router in Angular 7: A Step-by-Step Guide

Within my sidebar navigation component, the sidebar.component.html file is structured as follows: <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top" id="sideNav"> <a class="navbar-brand" href="#page-top"> <span cl ...

Tips for Modifying the currentUrl identifier in Angular 2

I am trying to change the ID property of my currentUrl object within my component. My goal is for the ID to update and then fetch the corresponding data based on that ID. However, I keep encountering this error message: "Cannot assign to read only propert ...

Getting exported members through Typescript Compiler API can be achieved by following these steps:

I am currently working on a project hosted at https://github.com/GooGee/Code-Builder This particular file is being loaded by the Typescript Compiler API: import * as fs from 'fs' Below is a snippet of my code: function getExportList(node: t ...

Tips for passing the indexes of an array within nested ngFor loops in Angular

I have a 2D grid in my component that is created using nested ngFor loops, and I want to make certain grid elements clickable under specific conditions so they can call a function. Is there a way for me to pass the index of the clicked array element to the ...

Adding an array into a pre-existing two-dimensional array for Highcharts integration: A step-by-step guide

I have been struggling to find a way to insert an array into a two-dimensional array. No matter what method I use - inserting it as an array, as text, using array_push, etc. - it just doesn't achieve the desired outcome. Below is a snippet of code th ...

I'm looking to find the Angular version of "event.target.value" - can you help me out?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/pages/home/home.component.html I am currently working on getting the dropdown menu to function properly for filtering the flags displayed below it. My initial thought was to replicate the search ...

Signing in to a Discord.js account from a React application with Typescript

import React from 'react'; import User from './components/User'; import Discord, { Message } from 'discord.js' import background from './images/background.png'; import './App.css'; const App = () => { ...

The TSX file is encountering difficulty rendering an imported React Component

Upon attempting to import the Day component into the Week component (both .tsx files), an error is thrown: Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. ...

Using GSAP in an Ionic application

What is the best way to add the GSAP library to an Ionic project? Simply running npm install gsap doesn't seem to work when I try to import it using: import { TweenMax, TimelineMax} from "gsap"; I am currently using TypeScript. Thank you. ...

In Javascript, check if an item exists by comparing it to null

I am working with a dropdown list that can be used for various types of data. Some of the data includes an isActive flag (a BOOLEAN) while others do not. When the flag is absent, I would like to display the dropdown item in black. However, if the flag exis ...

Tips for Maintaining User Data Across Pages in React using React-Router-Dom and Context

I've been tackling the login functionality of a client-side application. Utilizing React alongside TypeScript, I've incorporated react-router-dom and Context to manage the user's data when they log in. However, upon refreshing the page, the ...

When I attempt to conceal the filter within mat-table using *ngIf, I encounter an issue where I am unable to read the property 'value' due to it being

After creating a mat-table, I encountered an issue when trying to show and hide my input filter area using a button. If I use *ngIf="showInputFilter" to hide the filter area, I receive the error message Cannot read property 'value' of u ...

Unclear value of button when being passed

In my Welcome.html file, I am attempting to send the value of a button to a function that simply logs that value. This function is located in a functions class that has been imported into my welcome.ts file. <ion-content padding id="page1"> <h1 ...

The act of employing `Function.prototype.run` within an Angular TypeScript class is deemed as illegitimate

Is there a way to globally define a new function called run within my Angular component as shown below? Function.prototype.run = function (delay: number) { // some content; }; However, the compiler shows an error that the Property 'run' does n ...

Retrieve data from a MongoDB collection based on a specific index field

I am looking to extract only the "thetext" field from a specific index in my database when the value of "comment_count" is 1. This is the query I have tried: db.getCollection('mongotesi').find({},{'bug.long_desc.1.thetext':'1&apo ...

What are some ways to incorporate inline TypeScript Annotations into standard JavaScript code?

If you're using VSCode, there's a new feature that allows you to implement type checking for traditional JavaScript files. There are instances where I wish to specify the type of a variable or parameters in a method or function to enhance auto-co ...

Conditionally remove elements from an array with multiple dimensions

I am faced with the following array structure: ["balance"]=> array(5) { [0]=> array(3) { ["balance"]=> string(4) "0.00" ["id_item"]=> string(3) "540" ["item"]=> string(7) "Lampada" } [1] ...