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

Issue with Angular 4: Radio button defaults not being set

After hardcoding the value in component.ts, I am able to see the pre-selected radio button. However, when attempting to retrieve the value from sessionStorage, it does not work as expected. The value is visible in the console though. Could someone please ...

Typescript incompatibility causing errors with Vue components

I am encountering an issue while using typescript 2.8.3, ts-loader 3.5.0 (as I'm using webpack 2), and vue 2.5.16. The problem arises when attempting to define components in a Single File Component (SFC) like the code snippet below: <script lang=" ...

When using TypeORM's findOneBy method, if the search result

In order for the entity to have both identifiers, I require it to possess the Id and the _id export class ScriptSequencesExecutionEntity { @PrimaryGeneratedColumn({ name: 'id' }) _id!: string; @ObjectIdColumn() id: number; @AutoMap() ...

Displaying properties of objects in javascript

Just starting with JavaScript and struggling to solve this problem. I attempted using map and filter but couldn't quite implement the if condition correctly. How can I find the records in the given array that have a gender of 0 and color is red? let s ...

Can someone guide me on how to organize a div structure into a table format with the help of JQuery

I am new to JQuery and I have created a table using divs instead of the traditional table structure. Each row has the same ids, which I thought would help me sort the table. Here's an example of my code: <div class="column_title">Column 1</ ...

Implementing the 'colSpan' attribute in ReactJS

I encountered an error saying "Type string is not assignable to type number" when attempting to include the colSpan="2" attribute in the ReactJS TypeScript code provided below. Any suggestions on how to resolve this issue? class ProductCategoryRow exten ...

Update the component to display the latest information from the Bryntum grid table

In the Vue component, I have integrated a Bryntum grid table along with a bar chart. Clicking on one of the bars in the chart should update the data displayed in the Bryntum grid table. However, I've encountered difficulty in reloading the entire Bryn ...

:id Path replaces existing routes

My route configuration looks like this: const routes: Routes = [ { path: '', component: UserComponent, children: [ { path: '', component: LoginComponent }, { path: 'signup', component: SignupComponent } ]}, ...

Utilizing TypedPropertyDescriptor to limit decorators in Typescript when using decorator factories

When it comes to restricting what a decorator can apply on, the standard method involves using a TypedPropertyDescriptor like so: export function decorator(target, key, TypedPropertyDescriptor<T extends ...>) {...} While this approach works well whe ...

Serve both .ts and .js files to the browser using RequireJs

In my ASP.NET Core Project, the following files are present: greet.ts export class WelcomMesssage { name: string; constructor(name: string) { this.name = name; } say(): void { console.log("Welcome " + this.name); } } GreetExample.ts import * as ...

The 'Server' type is not designed to be generic

Out of nowhere, I encountered the following error: TypeScript: ./..\..\node_modules\@types\ws\index.d.ts:328:18 Type 'Server' is not generic. Angular CLI: 13.3.11 Node: 16.13.2 Package Manager: npm 8.1.2 OS: win3 ...

Splitting a string in Typescript based on regex group that identifies digits from the end

Looking to separate a string in a specific format - text = "a bunch of words 22 minutes ago some additional text". Only interested in the portion before the digits, like "a bunch of words". The string may contain 'minute', & ...

Angular's FormGroup for reactive forms is a powerful feature that allows for

Why am I unable to type in the input field before setting a value? html <form action="" [formGroup]="titleForm"> <input class="note-title" type="text" formControlName="title"> </form> ...

turning off next.js server side rendering in order to avoid potential window is undefined issues

I am currently managing a private NPM package that is utilized in my Next.js project, both of which are React and Typescript based. Recently, I integrated a graph feature into the NPM package and encountered an issue where any reference to window within t ...

To remove items with duplicate keys in PHP, keep only the one with the smallest value

I am facing a challenge with an array that needs to have elements deleted based on certain criteria. Specifically, I want to remove elements from the array that have the same time, keeping only the one with the lowest amount. While I understand the concept ...

In TypeScript, Firestore withConverter may return a QueryDocumentSnapshot instead of the expected Class object

I'm currently exploring the usage of Firestore's withConverted method in Typescript to retrieve queries as instances of my customized class. Custom EventConverter Class import Event from "@/models/Event"; class EventConverter implemen ...

How can I customize the visibility toggles for the password input field in Angular Material?

Currently immersed in the Angular 15 migration process... Today, I encountered an issue with a password input that displays two eyes the first time something is entered in the field. The HTML code for this is as follows: <mat-form-field appearance=&qu ...

Most effective method for initiating model class attributes

Is there a more efficient way to initialize model classes without explicitly defining each member as undefined? The original concept was to be able to simply use super(data); in extended classes. class Model { construct(data: any) { Object.ke ...

A method for comparing two arrays containing identical objects and then storing the results in a variable

I have an item stored within two other items called formKeyValues and form formKeyValues https://i.stack.imgur.com/nRfiu.png form https://i.stack.imgur.com/eDpid.png I am looking to extract only the keys and values from formKeyValues and place them in ...

Here's a revised version: "How to link a lambda layer with a function in a serverless.ts file using the

When working with the serverless framework using the typescript template, a serverless.ts file is generated. I am currently integrating lambda layers with existing functions and encountering a typescript error. The error message reads: "Type '{ Ref: ...