How to Alphabetize an Array of Strings Containing Numbers using TypeScript and Angular

I'm working with an array that looks like this:

arr = ["100 abc", "ad", "5 star", "orange"];

The goal is to first sort the strings without numbers at the beginning, then sort the strings with numbers added at the end. The numbers are to be omitted and the strings sorted alphabetically by name.

The expected output should look like this:

ad, orange, 100 abc, 5 star.

Do you have any suggestions for how I can achieve this in TypeScript/Angular?

Answer №1

Here's a possible implementation:

const startsWithNumber = (str) => /^\d/.test(str);

const extractAfterNumber = (str) => str.match(/^\d+\s(.*)/)[1];

const compareStrings = (a, b) => {
  if (startsWithNumber(a)) {
    if (startsWithNumber(b)) {
      // Both strings start with numbers, comparing the rest of the strings
      return extractAfterNumber(a) < extractAfterNumber(b) ? -1 : 1;
    } else {
      // String A starts with number but B does not, placing B first
      return 1;
    }
  } else if (startsWithNumber(b)) {
    // String B starts with number but A does not, placing A first
    return -1;
  } else {
    // Neither string starts with a number, comparing full strings
    return a < b ? -1 : 1;
  }
};

const array = [ "100 apples", "banana", "5 stars", "orange"];
const sortedArray = array.sort(compareStrings);
// ["banana", "orange", "100 apples", "5 stars"]

Answer №2

This particular inquiry pertains to partitioning rather than organizing. The task can be effortlessly accomplished by utilizing two filter functions:

outcome = [
    ...arr.filter(a => !/\d/.test(a)),
    ...arr.filter(a =>  /\d/.test(a)),
]

Answer №3

Here is a code snippet for you:

const arr = ["100 abc", "ad", "5 star", "orange"]
arr.map(item => {
        return item.split(' ').map((subItem: string) => +subItem ? +subItem : subItem)}
        ).sort((a,b) => {
            if(a.find((item: any) => typeof item === 'number')){
                return 1;
            }else return -1
    }).map(item => item.join(' '))

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

The ES6 import feature conceals the TypeScript definition file

I currently have two definition files, foo.d.ts and bar.d.ts. // foo.d.ts interface IBaseInterface { // included stuff } // bar.d.ts interface IDerivedInterface extends IBaseInterface { // more additional stuff } Initially, everything was funct ...

Is it possible to compare every element in an array with one another using an asynchronous process in NodeJS?

I am currently utilizing Resemble.js for image comparison within my web application. I have an array of image URLs that I need to compare with each other in order to calculate a unique score for each image. For example: [url1, url2, url3, url4] The minimu ...

Compiling Vue with TypeScript: Troubleshooting common errors

Using Vue Components with Templates Multiple Times in TypeScript I am working on utilizing a component with a template multiple times within another component. The code is split between a .html file and a .ts file. The .html file structure is as follows: ...

Which specific file(s) do I need to modify when incorporating dependencies in Node.js?

I am currently grappling with the challenge of integrating Multer into my Node.js application, but I am facing difficulty in determining the appropriate location for the code. Within Node.js, particularly while using Express, there exist two files: bin/ww ...

What is the best way to maintain an active PostgreSQL connection?

Essentially, I establish my database client using the following code: client = new pg.Client(conString); client.connect(); However, after a period of inactivity on the database, the client connection is likely dropped and results in this error message: ...

It seems that JavaScript is unable to detect newly added elements following an AJAX request

One issue I'm facing is that when an element loads data based on a clicked block, all javascript functionalities break. Currently, using Ajax, I load an entire PHP file into my index after sending a variable to it. For example: If Block 1 is clicked ...

Efficient JavaScript File Parsing with the Use of Breakpoints

Currently, I am developing a small web application that requires the user to upload a .csv file, which is then parsed into an array using JavaScript. However, I have encountered an issue where the JavaScript code only functions properly when I have develop ...

Issues arise when attempting to manipulate the DOM with ng-view in AngularJS

Apologies for not providing the code due to its length. I have a simple application with a single module, controller, and ng-view/routProvider. In my controller, when I use console.log(angular.element('div').length), it correctly shows that ther ...

Angular example of Typeahead feature is sending a blank parameter to the backend server

I am currently trying to implement a similar functionality to the example provided at this link in my Angular frontend application. The goal is to send a GET request to my backend with the search parameter obtained from an input field. However, even thoug ...

I am having trouble getting JQuery tablesorter to work, what am I missing?

As a newcomer to jQuery, I am attempting to implement Tablesorter, but unfortunately, it does not seem to be functioning properly on my table (the styling remains unaffected by the tablesorter css, and the sorting functionality is non-existent). Below is ...

Discovering the droppable container that a draggable element is positioned within

Currently, I am utilizing jQuery UI for drag and drop functionality. My main goal is to determine which droppable area a draggable element has been placed in. Can anyone offer assistance? Below is the code I am working with: $(".draggable").draggable({ ...

Choose a different option when there is a change

Here is an example of JSON data: [{ "user_id": "113", "employe_first_name": "Asaladauangkitamakan", "employe_last_name": "Nasibb" }, { "user_id": "105", "employe_first_name": "Ryan", "employe_last_name": ...

Validating a model in Mongoose: Best practices for updating data

I am facing an issue with my model. It seems that while creating, incorrect information is prohibited, but when editing, it is allowed. How can I prevent this from happening? var userSchema = new Schema({ cartaoCidadao: { type: String, require ...

Ways to prevent npm script from running automatically in the background

When working with npm scripts, I have a situation where some tasks need to run in parallel. My setup looks something like this: ... scripts: { "a": "taskA &", "preb": "npm run a", "b": "taskB" } ... Everything works well so far! But I am won ...

Attempting to show different fields depending on the chosen option

Having an issue with the signup process for my team and competition setup. I want to implement a feature where, if the user selects 'Competition', the promo code field will be displayed. However, this field should only appear when 'Competiti ...

Omit specific object properties within a foreach loop in jQuery AJAX

Check Out This Fiddle Example I am currently working with a PHP file that returns JSON data for main content along with an additional property for pagination. I am looking for a way to exclude the pagination property when iterating over the data in a fore ...

Encountering this issue despite confirming the presence of data on the line before! What could be the missing piece here? Error: Unable to access property 'includes' of undefined

Here is the situation.. I'm retrieving data from a database and storing it in an array of objects. These objects represent articles. I am working on implementing a filter system based on categories. The objective is to apply a filter that checks for a ...

What is the method for sending parameters to PHP from an HTML file using AJAX?

My protfolio.html file contains a table #gallery with different categories. I want to dynamically update the content of the #gallery based on the selected category using ajax. I have a php file that scans a specific folder for images related to the categor ...

Generate a versatile Union type featuring a mapped property

I am currently working with different types of data enum DataTypes { Email = 'email', Checkbox = 'checkbox', } type DataTypeValues = { [DataTypes.Email]: string; [DataTypes.Checkbox]: boolean; }; type Type1<T extends DataTy ...

Implementing the fetch API with radio buttons in a React Native application

I found a useful package for radio buttons called react-native-flexi-radio-button. Currently, I'm working on displaying API results within radio buttons. The API response provides 4 options, and my goal is to render text alongside the corresponding ra ...