Arrange an array of objects using the natural sorting order within a forEach loop

I am facing an issue where I am attempting to sort an array of objects, but nothing seems to be happening. Do I require another function to sort naturally alphanumeric, or is the forEach method causing a problem?

   element.items[x] = [
  {
    "title": "033 - Riegel, Freizeitaktivitäten",
  },
  {
    "title": "011 - Psychosomatischer Einstellungsfragebogen (ZPID-Standard 9001406)",
  },
  {
    "title": "047 - Wunschprobe (ZPID-Standard 9004592)",
  },
  {
    "title": "014 - Exploration II, allgemeine und vergangene Lebenssituation",
  },
  {
    "title": "006 - Beurteilung des Gesamteindrucks",
  },
  {
    "title": "015 - Exploration III, allgemeine und zukünftige Lebenssituation",
  },
  {
    "title": "016 - Befragung zur Familie und Angehörigen",
  }
]


this.dokumentation.forEach( element => {
  console.log(element.items.sort((a, b) => (a.title > b.title) ? 1 : -1));
});

Answer №1

One approach is to extract numbers from a string, then sort the array:

let sortedNums = items.sort((first, second) => parseInt(first.text) - parseInt(second.text));
console.log(sortedNums);

Answer №2

Instead of utilizing a for each loop, we can streamline the process by sorting elements directly.

let sortedArray = element.items[x].sort((a, b) => (a.title > b.title) ? 1 : -1);
console.log(sortedArray);

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

How can I hide the title bar on screens in expo?

As a newcomer to the world of react-native, I rely on YouTube tutorials to assist me in creating projects. Currently, I am working on developing an expo ui-app, however, each screen I create displays a title at the top, such as this example: https://i.ssta ...

The *ngFor directive is not displaying any items

I'm facing an issue with my code. I am using *ngFor to display some data, but something seems to be off. Here is the structure of my code: In a src/app/mock-heroes.ts file: import { Hero } from './hero'; export const HEROES: Hero[] = [ { i ...

Guide on creating a generic type that depends on the arguments provided, specifically a union type

I am dealing with the following similar types: class ActionFoo { action: 'foo'; foo: string; } class ActionBar { action: 'bar'; bar: number; } In addition, I have some handler functions for each type of defined "action", such a ...

The CORS policy has blocked access to XMLHttpRequest at a certain URL from a specific origin URL

I have come across an issue with CORS while working on my frontend. The CORS configuration works perfectly fine on my local host (development environment), but when I deploy the application to heroku, I encounter this error message. Access to XMLHttpReque ...

What is the best way to verify promises using HttpTestingController?

Within my angular 2 application, I have a data service that transforms http observables into promises to enable the use of async/await functionality. Here's an example: async getCustomer(id: number): Promise<Customer> { return await this._ht ...

Testing the functionality of functions through unit testing with method decorators using mocha and sinon

I have a class method that looks like this: export class MyClass { @myDecorator() public async createItem(itemId: string, itemOptions: ItemOption[]): Promise<boolean> { // ... // return await create I ...

Sass could not compile due to an i18n error - the resource file was not located

Within our Angular 4 application, we are encountering an issue while trying to implement i18n. The problem arises when running npm run i18n as it displays an error stating 'Resource file not found': Error: Compilation failed. Resource file not ...

Eliminating Body Tag Margin in Angular 4: A Step-by-Step Guide

In the Angular 4 project, the app.component.html file does not include a body tag that can be styled to eliminate the padding associated with the body tag. https://i.sstatic.net/5QS9x.jpg An attempt was made in the app.component.css file to remove the ma ...

How to resolve the issue of a sticky header not functioning properly with a resizable column in Primeng

Currently, I am facing an issue while trying to incorporate both column resize functionality and sticky header in my table. Interestingly, the sticky header feature works perfectly fine when used alone without the column resize. However, when I attempt to ...

Ways to retrieve the component name from a service in Angular without relying on private APIs such as view container refs

How can I access the component name inside a service that is calling a method within the service? I have tried using console.log(this.vcr['_view'].component) and console.log(this.vcr['_view'].component.constructor.name), but they do not ...

Angular CLI version 13 does not support the execution of "ng" commands

Recently, I upgraded the Angular CLI to version v13 globally. However, upon attempting to use the ng command, I encountered a puzzling error message: https://i.sstatic.net/gAgB4.png After consulting advice provided here, I learned that Angular v13 is sup ...

Designing Angular 1 table row components with future migration to Angular 2 in consideration

Issue with AngularJS nested directives placement outside parent element Encountering the same challenge in my project using Angular 1.4, but I am also aiming to construct the rows as Angular 2 components which prevents me from using "replace: true". I am ...

What's the trick to aligning the label on the material-ui text field to the right side?

I am working on a React project with an RTL layout using material-ui and typescript. I am struggling to align the label of a text field to the right. Can anyone help me with this? https://i.sstatic.net/UrkIF.jpg ...

Troubleshooting Angular 2 Karma Error: Module Parse Failed due to missing loader for file type

I'm currently configuring Karma for my Angular 2 application and I seem to be facing an issue with a missing plugin. Could anyone provide assistance with this matter? I am utilizing the following repository as a reference: https://github.com/AngularC ...

"Unlocking the Secrets: Mastering Step Index Manipulation in Angular Arch

Looking for tips on changing the step index in Angular Arch Wizard. I have two forms on the same page and need to navigate to a specific step. Any ideas? <aw-wizard > <aw-wizard-step > <form role="form" > < ...

I'm experiencing a delay in receiving real-time values with Angular Observables

My project involves 2 components (Menu and Header) and one Service. The goal is for the menu to send the selected item text to the service, which will then pass it to the header for display. While I have successfully sent data to the service, I am facing a ...

effects of material ui buttons

I have implemented two material ui buttons on my page. <Button variant="contained">Apply</Button> <Button variant="contained">Remove</Button> I am looking to add some functionality where a description of what ea ...

Components are not displaying Angular style as expected, even though host selectors are being used

I am facing a problem with the styling of components in my Angular projects. I am unable to make it work properly. To explain the issue, I started a new project using Angular CLI (CLI 6.0.8, angular 6.1.0). In this project, I created a test component where ...

The attribute "JSON" is not found within the Object type

When attempting to parse a JSON configuration file using the code below: this.http.get('assets/env/env.json').pipe(map( res => res.json())).pipe(catchError((error: any): any => { console.log('Configuration file "env.json" c ...

Can you explain the distinction between using tsserver and eslint for linting code?

As I work on setting up my Neovim's Native LSP environment, a question has arisen regarding JS/TS linter. Could someone explain the distinction between tsserver and eslint as linters? I understand that tsserver is a language server offering features ...