Arrange elements within an array according to a specific property and the desired sorting sequence

Looking for a way to sort an object array in Angular 16+ based on status. The desired status order is:

[N-Op, Used, Unknown, Op]

Here's the sample data:

const stockList = [
    {
      'heading': 'SK',
      'status': 'N-Op',
    },
    {
      'heading': 'SKU',
      'status': 'Op',
    },
    {
      'heading': 'Uniliver',
      'status': 'Op',
    },
    {
      'heading': 'Bugati',
      'status': 'Unknown',
    },
    {
      'heading': 'Bugati',
      'status': 'N-Op',
    },
  ];

How can I achieve the expected result as shown below?

const stockList = [
    {
      'heading': 'SK',
      'status': 'N-Op',
    },
    {
      'heading': 'Bugati',
      'status': 'N-Op',
    },
    {
      'heading': 'Bugati',
      'status': 'Unknown',
    },
    {
      'heading': 'SKU',
      'status': 'Op',
    },
    {
      'heading': 'Uniliver',
      'status': 'Op',
    }
  ]; 

Answer №1

To efficiently sort the stockList based on a custom logic, utilize the Array.prototype.sort() method. Define the comparison logic by considering the index in the sortOrder array.

Make sure that all values of status are present in the sortOrder array.

const sortOrder = ["N-Op", "Used", "Unknown", "Op"];

let sortedStockList  = stockList.sort((a, b) => {
    let xIndex = sortOrder.indexOf(a.status);
    let yIndex = sortOrder.indexOf(b.status);

    if (xIndex < yIndex)
        return -1;
    else if (xIndex > yIndex)
        return 1;
    else
        return 0;
});

(Optional) If you wish to further sort based on the heading, simply replace return 0; with

return a.heading.localeCompare(b.heading);

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

Merge mocha with Typescript, and include the watch feature

For my project, I have set up mocha to test my Typescript code. The issue arises when running the command: mocha ts/test --compilers ts:typescript-require Every time I make a change, it fails with an error message like this: error TS2307: Cannot find mo ...

Rxjs: Making recursive HTTP requests with a condition-based approach

To obtain a list of records, I use the following command to retrieve a set number of records. For example, in the code snippet below, it fetches 100 records by passing the pageIndex value and increasing it with each request to get the next 100 records: thi ...

How can you determine if a specific variable exists within an array using an if statement?

Currently, I have designed a program that incorporates methods such as inputArray, selectionSort, binarySearch, and printArray. However, I am facing some difficulty while working on the main method. I need assistance in creating the main method that calls ...

Struggling to delete event listeners in TypeScript using object-oriented programming with JavaScript

After researching the issue, I have discovered that the onMouseUp event is being fired but it is not removing the EventListeners. Many individuals facing a similar problem fail to remove the same function they added initially. Upon reading information fr ...

What causes the typings for Partial Record to be undefined when using Object.values?

When I retrieve Object.values from a Partial Record, the values consist of a combination of what I anticipated and undefined. const example: Partial<Record<string, number>> = {} const values = Object.values(example) // The type for values is u ...

``If you're looking to integrate a 360-degree product viewer into your Angular application, here is a

I am in need of showcasing a 360 Product viewer consisting of an array of 36 car images in base64 format. Despite attempting to utilize the angular-three-sixty Package by @mediaman, I was only met with an empty canvas. Does anyone have experience in implem ...

Vue3 with Typescript may either display an error message or remain empty when handling props

I've been attempting to utilize the default Quasar card component in order to display data received from props. Unfortunately, I haven't had any success as my component remains empty and I keep encountering various errors with each attempt. Rece ...

Using Angular to automatically update the user interface by reflecting changes made in the child component back to the parent component

Within Angular 5, I am utilizing an *IF-else statement to determine if the authorization value is true. If it is true, then template 2 should be rendered; if false, then template 1 should be rendered. Below is the code snippet: <div *ngIf="authorized; ...

Typescript - Keeping a log of object keys along with their corresponding key type values

Imagine having the following scenario where you need to create an object with keys that are transformed versions of the original type's values: export type CCDTypes = { AuthorisationCaseEvent: AuthorisationCaseEvent, AuthorisationCaseField: Author ...

Retrieve the input type corresponding to the name and return it as a string using string template literals

type ExtractKeyType<T extends string, K extends number> = `${T}.${K}`; type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends readonly unknown[] ? ExtractKeyType<Key, 0 | 1> : T[Key] extends Record<str ...

Access values of keys in an array of objects using TypeScript during array initialization

In my TypeScript code, I am initializing an array of objects. I need to retrieve the id parameter of a specific object that I am initializing. vacancies: Array<Vacancy> = [{ id: 1, is_fav: this.favouritesService.favourites.find(fav = ...

Loading the value of a Subject variable in an Angular 2 application using Typescript

I am currently developing an Angular2 application where I am loading data from a service into my component as a subject. public type1Choisi: any; constructor( public formeService: FormeService, ...) { this.formeService._type1.subscribe(type1 => ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

Angular4 Error: Unable to link to 'ngClass' as it is not recognized as a property of 'input'

Currently, I am facing an issue in my project where I am utilizing lazy loading. Specifically, within my registration module, I am attempting to utilize the [ngClass] directive to append an 'invalid' class when there are validation errors present ...

Ensure that the date is valid using Joi without transforming it into UTC format

Is there a method to validate a date using @joi/date without converting it to UTC? I need to ensure the date is valid before storing it in the database. Here's what I've attempted: const Joi = require('joi').extend(require('@joi/ ...

Is there an alternative method to incorporate the 'environment.ts' file into a JSON file?

In my Angular application, I need to import assets based on the env configuration. I am attempting to extract the patch information from environment.ts and save it into my assets as a json file. However, I am unsure of the proper method to accomplish this. ...

What is the method for including word boundaries in a regex constructor?

export enum TOKENS { CLASS = 1, METHOD, FUNCTION, CONSTRUCTOR, INT, BOOLEAN, CHAR, VOID, VAR, STATIC, FIELD, LET, DO, IF, ELSE, WHILE, RETURN, TRUE, FALSE, NULL, THIS } setTokenPatterns() { let tokenString: s ...

Ensuring type signatures are maintained when wrapping Vue computed properties and methods within the Vue.extend constructor

Currently, I am trying to encapsulate all of my defined methods and computed properties within a function that tracks their execution time. I aim to keep the IntelliSense predictions intact, which are based on the type signature of Vue.extend({... Howeve ...

Using Jest in Typescript to simulate fetch responses

I am currently facing an issue with mocking the global fetch function using Jest and dealing with the Response type. Specifically, I only require the response.ok and response.json properties, but I am struggling to set the return data of fetch without spec ...

What is the best way to gather the "name" and "value" attributes from a designated section of a form using JavaScript and store them in an array?

How can I extract the "name" and "value" attributes from a specific section of a form and store them in an array using JavaScript? Here is the section of the form in question: <div class="multiPickerForm"> <input type="text" name="Id" value="1"& ...