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

Experience the advanced NgPrime p-dropdown template with templating, filtering, and a clear icon that collapses when wrapped within a form element

Check out this link for a demo Whenever I enclose the code below in a </form> element, the drop-down menu collapses. <h5>Advanced with Templating, Filtering and Clear Icon</h5> <p-dropdown [options]="countries" [(ngModel)]=& ...

Exploring a JSON object using PlaywrightWould you like to know how

Greetings! Here is a snippet of code that I have, which initiates an API call to a specific URL. const [response] = await Promise.all([ page.waitForResponse(res => res.status() ==200 && res.url() == & ...

How can I save a TypeScript object to Firebase using serialization?

Having an issue: Within my angular application, I have implemented a lot of classes with inheritance. However, upon attempting to save these objects to Firebase, I encountered an error indicating that I am trying to persist custom objects which is not supp ...

Angular 8 - Customizing primeng/fullcalendar Appearance Based on Event Type (Looping Events) and Cell Background Color

This is how I have integrated fullcalendar into my Angular 8 application: calendar.component.ts: export class MyCalendarComponent implements OnInit { public plantedActivities: PlantedActivityModel[] public actuatorActivities: ActuatorActivityModel ...

Creating a Custom FlatList Content Container with React Native

Is it possible to customize FlatList items with a custom component? I want to create a setup where my FlatList items are encapsulated within a custom component similar to the following: <ScrollView pt={8} px={16} pb={128} > <Card e ...

Encountering CORS policy block when attempting to post data using Geoserver API through Angular

I'm currently working on Angular and I need to integrate the Geoserver API to publish spatial database data. Previously, I successfully used PHP Curl with the API and now I want to incorporate it into my Angular app. It's worth mentioning that ...

Guide on linking action observables to emit values in sync before emitting a final value

If you're familiar with Redux-Observable, I have a method that accepts an observable as input and returns another observable with the following type signature: function (action$: Observable<Action>): Observable<Action>; When this method r ...

How can a class be added to only the initial row in Angular2?

I'm looking to dynamically add a CSS class under certain conditions. Within the code snippet below, I am trying to assign the RowHeaderCSS class to the first row of the table. However, it doesn't seem to be working as expected. Can anyone provid ...

Create an array of arrays within a loop using TypeScript

My application contains an object with dates and corresponding time arrays. The console log output is displayed below: 32: { 1514160000: Array [ 1200, 1500 ], 1514764800: Array [ 1200, 1500 ], 1515369600: Array [ 1200, 1500 ], 1515974400: Array [ 700, 12 ...

TypeScript Type Mapping for HTML Element Tags

I am currently working on a TypeScript + React project and facing an issue with the polymorphic as prop in one of my components. Specifically, I want to restrict this prop to only accept HTML tags, excluding ReactNodes or JSX Elements. Unfortunately, I hav ...

Angular 17 isn't notifying child component of signal changes

In the statistics module, I have a signal that specifies the type of charts to display and this signal is updated through a radio button group. The signal: typeSignal = signal<string>('OIA') The radio buttons for setting the : <div clas ...

In Next.js, the Typescript compiler does not halt when an error occurs

I am looking to incorporate Next.js with TypeScript into my project. I followed the official method of adding TypeScript to Next.js using npx create-next-app --typescript. Everything seemed fine, but when a TypeScript error occurs (e.g. const st: string = ...

What steps are involved in implementing ts-transformer-keys in a Next.js project?

I am trying to extract keys from an interface as a string array so that I can iterate over them. After doing some research on stackoverflow, I found out that I need to use a library called 'ts-transformer-keys'. In my Next.js project, which invol ...

ReactJS: A single digit input may result in the display of numerous '0's

My goal is to have a small box that only allows one digit, but it seems to work fine until I try to input multiple '0's. Then the box displays multiple 0000 persistently. Here is the code snippet: const InputBox = () => { const [value, ...

Utilize environment variables to access system information when constructing an Angular 2 application

In order to build my Angular application, I want to utilize a single system variable. System Variable server_url = http://google.com This is how my Environment.ts file looks: export const environment = { production: false, serveUrl: 'http://so ...

Enrich your TypeScript code by unleashing the power of enum typing in overloading logical

I have a custom enum called PathDirection that represents different directions export enum PathDirection { LEFT="LEFT"; RIGHT="RIGHT"; }; Within my code, I need to toggle between the two directions. For example: let currentDire ...

Transforming a JavaScript chained setter into TypeScript

I have been utilizing this idiom in JavaScript to facilitate the creation of chained setters. function bar() { let p = 0; function f() { } f.prop = function(d) { return !arguments.length ? p : (p = d, f); } return f; } ...

Display the spinner until the data is successfully updated in the DOM using Angular

Dealing with a large dataset displayed in a table (5000 rows), I am attempting to filter the data using column filters. When applying the filter, I have included a spinner to indicate that the filtering operation is in progress. However, due to the quick ...

Transforming Angular application into a microfrontend architecture

I've successfully developed an Angular application and now I'm looking to transform it into a microfrontend application using the single SPA approach. Can someone please advise me on the necessary steps to achieve this? Also, I'd appreciate ...

Add integer to an array of strings

Currently, I am utilizing an autocomplete feature and aiming to save the IDs of the selected users. My goal is to store these IDs in a string array, ensuring that all values are unique with no duplicates. I have attempted to push and convert the values u ...