Sorting JSON arrays in Typescript or Angular with a custom order

Is there a way to properly sort a JSON array in Angular? Here is the array for reference:

{"title":"DEASDFS","Id":11},
{"title":"AASDBSC","Id":2},
{"title":"JDADKL","Id":6},
{"title":"MDASDNO","Id":3},
{"title":"GHFASDI","Id":15},
{"title":"HASDFAI","Id":1},
{"title":"ASDHFI","Id":9},

The desired order of the Id's should be as follows:

15,6,1,11,9,2,3

<div *ngFor="let field of fieldsData;let i=index;">
  <div class="form-inline assigned_text-box" [ngSwitch]="field.Id">

    <div class="col-md-2" *ngSwitchCase="15">
      <label>One</label>
    </div>
    <div class="col-md-2" *ngSwitchCase="6">
      <label>Two</label>
    </div>
    <div class="col-md-2" *ngSwitchCase="1">
      <label>Three</label>
    </div>
    <div class="col-md-2" *ngSwitchCase="11">
      <label>Four</label>
    </div>
    <div class="col-md-2" *ngSwitchCase="9">
      <label>Five</label>
    </div>
    <div class="col-md-2" *ngSwitchCase="2">
      <label>Six</label>
    </div>
    <div class="col-md-2" *ngSwitchCase="3">
      <label>Seven</label>
    </div>

  </div>
</div>

However, currently when using the ngSwitch condition, the items are displayed in the order they appear in the JSON data: 11,2,6,3,15,1,9

My goal is to display them in this particular order instead: 15,6,1,11,9,2,3. How can I achieve this custom sorting of the array?

Answer №1

To sort the array, you can use the Array#sort method.

// Define reference for sort order priority
const ref = {
  15: 0,
  6: 1,
  1: 2,
  11: 3,
  9: 4,
  2: 5,
  3: 6
};

let data = [{
    "title": "DEASDFS",
    "Id": 11
  },
  {
    "title": "AASDBSC",
    "Id": 2
  },
  {
    "title": "JDADKL",
    "Id": 6
  },
  {
    "title": "MDASDNO",
    "Id": 3
  },
  {
    "title": "GHFASDI",
    "Id": 15
  },
  {
    "title": "HASDFAI",
    "Id": 1
  },
  {
    "title": "ASDHFI",
    "Id": 9
  };
  
// Sort the data based on reference
console.log(
  data.sort((a, b) => ref[a.Id] - ref[b.Id])
)


You can also create a custom pipe for sorting by referring to this link: Angular 2 OrderBy Pipe

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

Incorrect deduction of the argument type for a higher-order function

If I wanted to create a function that takes an object of type T and another value, where the type P should somehow be restricted by T (for example, P should be an array of keys of T), I could easily write it like this: function customFunction<T, P exte ...

Angular 2 testing encounters an issue with ViewUtils when setBaseTestProviders() is used

Encountering an issue when utilizing the 'setBaseTestProviders(..)' method, a console error arises. Our current version of Angular is 2.0.0-rc.1. The test located at (test/areas-list.component.spec.ts) looks like this: import {setBaseTestProv ...

Adding connected types to a list using Typescript

Question regarding Typescript fundamentals. In my code, I have a list that combines two types using the & operator. Here is how it's initialized: let objects: (Object & number)[] = []; I'm unsure how to add values to this list. I attem ...

The functionality of the Drawer component in material-ui v1.0 seems to be incompatible with TypeScript

Every time I try to utilize Drawer from [email protected] using typescript, I encounter the following error: TS2322: Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Re ...

Premature conclusion of observable

I'm facing an issue with an element using the async pipe to subscribe to a Behavior Subject. showDiv$ = new BehaviorSubject<boolean>(false); showDivObv$ = this.showDiv$.asObservable().pipe( tap(() => console.log('here')), ...

TRPC error: The property 'useInfiniteQuery' is not found in the type '{ useQuery'

Issue with TRPC I am facing a problem with my tweetRouter that has a timeline query returning tweets and a NextCursor. However, I encounter an error when trying to access useInfiniteQuery in my components. ** Property 'useInfiniteQuery' does no ...

Is it required to double click checkboxes to uncheck them?

My checkboxes require 2 clicks to be unchecked, even though one click is enough to check them. This issue occurs in all 7 checkboxes and there is no onchange() function or similar in TS. import { Component, OnInit, Inject } from '@angular/core&apos ...

Utilizing Glassfish Application Server and MSSQL Database for Angular Front-End Authentication in Jakarta

Embarking on my journey in the realm of web development, I am eager to implement authentication for my full-stack application. Armed with Angular 13 on the front end, Jakarta 9 running on Glassfish app server, and MSSQL database, I find myself at a loss on ...

Utilizing handpicked information in Angular: A beginner's guide

Being new to Angular and programming in general, I am currently navigating through the intricacies of Angular and could use some guidance on utilizing selected data. For instance, I would like to use a personnel number view image here and send it to the b ...

Leverage the Nuxeo client SDK with Angular 6 for seamless integration with RESTClient in

Looking to integrate the Nuxeo ClientSdk with my Angular 6 client to consume its REST API, but facing issues due to the lack of typescript definitions for this JavaScript package. Tried importing the library into my project using the following code snippe ...

Effectively Monitoring Angular Router Link Status

Is anyone else facing an issue with router link active not working correctly when navigating to a route with a different ID? The class is applied on the first navigation, but not on subsequent navigations. Any solutions? This is my HTML file: <div clas ...

Challenges with Ionic 4 - Module '@angular/core/package.json' not found

Having some trouble with an Ionic 4 project code that works perfectly on my Mac but encounters an error when I try to run it on my Windows 10 PC. The specific error message states "Cannot find module '@angular/core/package.json'". Interestingly, ...

searchByTextContentUnderListItemAnchorTag

I would like to utilize the getByRole function for writing my test. However, I am encountering issues when using linkitem or 'link' as the role. It seems that I cannot find the desired element. // encountered error TestingLibraryElementError: The ...

Learn how to dynamically enable or disable the add and remove buttons in the PrimeNG PickList using Angular 2

I'm currently learning Angular 2 and I'm working on creating a dual list box using PrimeNG's pickList component (https://www.primefaces.org/primeng/#/picklist). Within the pickList, I have table data with 3 columns, along with ADD and REMO ...

Is it possible to interchange the positions of two components in a routing system?

driver-details.component.ts @Component({ selector: 'app-driver-details', templateUrl: './driver-details.component.html', styleUrls: ['./driver-details.component.css'] }) export class DriverDetailsComponent implements OnI ...

Using Angular 6 to Share Data Among Components through Services

I am facing an issue in my home component, which is a child of the Dashboard component. The object connectedUser injected in layoutService appears to be undefined in the home component (home userID & home connectedUser in home component logs); Is there ...

Eliminate perfect-scrollbar functionality on mobile devices

I have applied the perfect-scrollbar class with 'height: auto' on mobile screens, expecting it to work properly. It's functioning well in responsive mode on the web. However, it does not scroll on mobile devices. @media (max-width: 992px) { ...

Mastering the use of SVG icons in Angular 4+: A comprehensive guide

I have an icon.svg file with a collection of icons that I would like to use in my app, similar to how we display material icons. Does anyone have any ideas on how to include the file in the app and use these icons? I've tried looking for solutions a ...

DOM Manipulation in Angular

I encountered an issue in the spec file where DOMHelper was not found and could not be imported, despite adding it with "npm I dom-helpers". How can I resolve this error? I will also provide a screenshot for reference. Click here to view the image Module ...

The validation process in reactive forms is experiencing some issues with efficiency

Trying to debug an issue with my reactive forms - the repeatPassword field doesn't update as expected. When entering information in the "password" field, then the "repeatPassword" field, and back to "password", the second entry is not flagged as inval ...