Typescript custom sorting feature

Imagine I have an array

products= [{
"Name":'xyz',
'ID': 1
},
{
"Name":'abc',
'ID': 5
},
{
"Name":'def',
'ID': 3
}
]

sortOrder=[3,1,5]

If I run the following code:

sortOrder.forEach((item) => {
        products.sort((productA) => {
          if (productA.ID=== item) { return 1; } else { return -1; }
        });
      });

The sorting is not as per the order specified in sortOrder. I want to sort the products array based on the sortOrder mentioned in the sortOrder array. So, the output of the above should be,

{ "Name":'def', 'ID': 3 },{ "Name":'xyz', 'ID': 1 },{ "Name":'abc', 'ID': 5 }

Any suggestions?

Answer №1

Revised the solution to handle repeated values in the products list.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  products= [{
"Name":'xyz',
'ID': 1
},
{
"Name":'abc',
'ID': 5
},
{
"Name":'def',
'ID': 3
},{
"Name":'xyz',
'ID': 1
},
{
"Name":'abc',
'ID': 5
},
{
"Name":'def',
'ID': 3
},
{
"Name":'def',
'ID': 3
},
{
"Name":'def',
'ID': 3
}
]

sortOrder=[3,1,5];

sortProducts(){
  var tempSortedProducts :any[]=[];

  for(let idx=0; idx<this.sortOrder.length; idx++){

      this.products.forEach((product)=>{
        if(product.ID===this.sortOrder[idx]){
            tempSortedProducts.push(product)
        } 
      })
  }
  this.products = tempSortedProducts;
}
}

Link to Stackbliz Example: Custom Sort

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

Create an array using modern ES6 imports syntax

I am currently in the process of transitioning Node javascript code to typescript, necessitating a shift from using require() to import. Below is the initial javascript: const stuff = [ require("./elsewhere/part1"), require("./elsew ...

Framer Motion's AnimatePresence feature fails to trigger animations when switching between pages

I'm running into issues with the Framer Motion library, specifically with the AnimatePresence transition. I've managed to make it work in normal situations, but when I encapsulate my Routes within a custom implementation, the exit animation fails ...

Is there a way to identify which elements are currently within the visible viewport?

I have come across solutions on how to determine if a specific element is within the viewport, but I am interested in knowing which elements are currently visible in the viewport among all elements. One approach would be to iterate through all DOM elements ...

Looping Angular Components are executed

I am currently developing an Angular application and encountering an issue with my navbar getting looped. The problem arises when I navigate to the /home route, causing the navbar.component.html components to duplicate and appear stacked on top of each oth ...

Access exclusive content by subscribing now!

How can I return a reference to a subject from a service without allowing the receiver to call .next() on the subject? Let's say there is a service with a subject that triggers new events. class ExampleService { private exampleSubject = new Subjec ...

What is the best way to combine a set of k sorted lists?

def merge(list1, list2): results = [] while list1 and list2: if list1[0] < list2[0]: results.append(list1.pop(0)) else: results.append(list2.pop(0)) results.extend(list1) results.extend(list2) ...

Unlocking the power of module augmentation in Typescript: Enhancing library models within your app domain

I currently work with two applications that share the same code base for their models. I am interested in developing and sharing a library model using inheritance in TypeScript. For instance, Pet extends Author. In my current Angular application, I need ...

Tips for updating the font size of your MUI Accordion title

I was attempting to adjust the font size of the MUI-5 Accordion title. It seems like I need to override it, but I am unsure about how to do so with CSS in MUI-5. Instead of 'SX', it uses 'htmlSx'. When I tried using it, it did not produ ...

What is the injection token used for a specialized constructor of a generic component?

I created a versatile material autocomplete feature that I plan to utilize for various API data such as countries, people, and positions. All of these datasets have common attributes: id, name. To address this, I defined an interface: export interface Auto ...

Experimenting with a Collection of Items - Jest

I need to conduct a test on an array of objects. During the test coverage analysis of the displayed array, I found that the last object with the key link has certain conditions that are not covered. export const relatedServicesList: IRelatedServiceItem[ ...

The HTTP DELETE request encountered a TypeError, stating that error.json is not a valid function

Within my Angular application, there is a feature that involves a "delete button". When this button is clicked, a confirmation popup appears asking the user if they are certain they want to proceed with the deletion. If the user confirms by clicking ' ...

TSLint is unable to locate a custom module containing a custom d.ts file

I've been searching for a solution to this issue, but haven't found a definitive answer yet. My current challenge involves using the suncalc module with TypeScript. Since it doesn't come with its own typing file, I created one and saved it ...

The options passed to createReadStream in TypeScript do not accept {start: 90, end: 99}

After updating to TypeScript 1.6.2, I encountered an issue with my call to createReadStream(). The problem arises because the type definition in node.d.ts does not recognize 'start' and 'end' in the options parameter. var st = fs.crea ...

TypeScript is still throwing an error even after verifying with the hasOwnProperty

There exists a type similar to the following: export type PathType = | LivingstoneSouthernWhiteFacedOwl | ArakGroundhog | HubsCampaigns | HubsCampaignsItemID | HubsAlgos | HubsAlgosItemID | TartuGecko | HammerfestPonies | TrapaniSnowLeop ...

It seems that the Angular2-google-maps library is having trouble with installation

Attempting to install the angular2-google-maps library is resulting in errors. The desired library can be found at: The specific error encountered is displayed here: https://i.stack.imgur.com/L2vOY.png Any assistance with this issue would be greatly app ...

The main module's postinstall process is initiated before the sub-module's postinstall process

Update: I am seeking guidance on how to install a module from GitHub instead of npm. That's the main query. In case you're wondering why: I'm currently working on some confidential projects and prefer not to publish the code. As a result, ...

Alert: Angular has detected that the entry point '@libray-package' includes deep imports into 'module/file'

Recently updated the project to Angular 9.1 and now encountering multiple warnings from the CLI regarding various libraries, such as these: Warning: The entry point '@azure/msal-angular' includes deep imports into 'node_modules/msal/lib-com ...

The issue with functions not executing when triggered by HammerJS

In my application, there is a component that displays information for different days as they are cycled through using the functions dayUp() and dayDown(). Here is an example of how these functions are structured: dayUp() { if (this.dayCount == 7) { ...

Angular - developing a custom web element to enhance the project

Is there a way to convert a single module into a web component and integrate it within the same project? Specifically, I have 3 modules in my project and I am looking to transform only module1 into a web component and incorporate it seamlessly. Thank you! ...

How can TypeScript be used to enable CSV or PDF export in a material-react-table?

Is it possible to incorporate the ability to export data to CSV or PDF in a material-react-table? While I am familiar with how to do this with a Material UI table, I have not been able to find the same functionality for the material-react-table. Thank you ...