Sorting arrays in Typescript

Is there a way to alphabetically sort an array of objects in Typescript based on a specific field? The array I have currently looks like this - https://i.stack.imgur.com/fQ3PA.png I'm interested in sorting it alphabetically by the 'channel' field.

I attempted the following approach that I found online. Although it didn't throw any errors, it also didn't give me the results I was expecting.

 this.currentPickSelection = this.currentPickSelection.sort((a, b) => {
      if (a.channel > b.channel) {
        return 1;
      }
      if (a.channel < b.channel) {
        return -1;
      }
      return 0;

Answer №1

Your task involves sorting a multidimensional array using the array#sort method with this code:

this.currentPickSelection.sort((x, y) => x[0].category.localeCompare(y[0].category))

Answer №2

To solve this problem, you need to organize a list of objects.

Transform your JSON object into an array of multiple objects.

[
    {
        "pickCode":"",
        "cbsCode": "",
        "channel": "",
        "logo": "",
        "tag": ""
    },
    {
        "pickCode":"",
        "cbsCode": "",
        "channel": "",
        "logo": "",
        "tag": ""
    },
    {
        "pickCode":"",
        "cbsCode": "",
        "channel": "",
        "logo": "",
        "tag": ""
    }
]

Create a function that can be reused with similar logic but includes the toLowerCase() method as well.

private compare(a, b) {
 if (a.channel.toLowerCase() < b.channel.toLowerCase()) {
  return -1;
 }
 if (a.channel.toLowerCase() > b.channel.toLowerCase()) {
  return 1;
 }
 return 0;
}

Assuming the name of the variable holding the array of objects is channelDetails,

simply run

this.channelDetails.sort(this.compare);
to achieve the desired sorting result.

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

Typescript implementation for a website featuring a single overarching file alongside separate files for each individual webpage

Although I've never ventured into the realm of Typescript before, I am intrigued by its concept of "stricter JS". My knowledge on the subject is currently very limited as I am just starting to experiment with it. Essentially, I have developed my own ...

Angular is generating local caches of NPM packages within the designated .angular folder

Is there a way to turn off the caching in the main Angular project directory? I noticed this issue after setting up NVM last week. ...

After installing the latest version of Node.js, the stability of the Ionic environment

After updating nodejs from v8.1 to v12, my ionic environment is experiencing instability. Any suggestions on what needs to be updated? [abc]$ ionic cordova emulate android When running ng run app:ionic-cordova-build --platform=android, an unhandled exce ...

Invoke a function within a component, within that very component

Hey there, I've got an Angular 2 component with a @HostListener. My goal is to call a method from this component using the @HostListener. Check out the code snippet below for my attempt at implementing this: The Component import { Component, Host ...

Error: Unable to locate the custom module - TS2307

We have recently taken over a Next + TypeScript website from another developer and are attempting to create a new component that is heavily based on an existing one. I have duplicated the entire component and its subfolders at the same level as the origina ...

Using AngularJS $resource to send query strings instead of JSON objects in a POST request (Typescript)

Whenever I create a custom $resource action like this: getEntityResource(): ng.resource.IResourceClass<IEntityResource> { let addAction: ng.resource.IActionDescriptor = { method: 'POST', url: 'http://l ...

Having trouble removing or updating Angular Cli on a MAC device

Struggling with uninstalling angular cli on mac. npm remove -g @angular/cli ...

Angular: Defining variables using let and var

When working with TypeScript and JavaScript, we typically use either let or var to declare a variable. However, in Angular components, we do not use them even though Angular itself uses TypeScript. For instance, export class ProductComponent implements OnI ...

Utilizing OverlappingMarkerSpidifier in conjunction with sebm-angular2-google-map

I'm currently integrating OverlappingMarkerSpidifier using SebM Angular 2 Google Maps on angular2 2.0.0. After successfully loading the google maps API with the GoogleMapsAPIWrapper imported from the sebm module, I am running into an issue when execu ...

Having an excess of 32 individual byte values

My current project involves developing a permission system using bitwise operators. A question came up regarding the limitation of having only 32 permissions in place: enum permissions { none = 0, Founder = 1 << 0, SeeAdmins = 1 << ...

How can we effortlessly generate a times table using For loops and arrays?

As someone new to JavaScript, I am eager to learn. My goal is to create two "for" loops: one to save the values of the 6 times table up to 12x6 into an array called timesTable, and another to display these values in the console (e.g., 0 x 6 = 0). Thank y ...

Different types of subscriptions for forkJoin observable

I am currently making two API requests with typed responses and combining them using the Observable.forkJoin method. My goal is to store each of the results in separate typed variables. var observableOrganization: Observable<Organization> = this.get ...

Enhancing interface properties with type safety in a function declaration using Typescript

Consider the following scenario: interface Steps { stepOne?: boolean; stepTwo?: boolean; stepThree?: boolean; } let steps: Steps = {}; function markStepDone (step: ???) { steps[step] = true; } markStepDone('anything'); Is there a wa ...

In order to modify the PHP code in the file, I will need to update the JSON output that is currently being generated

I am currently using PHP code to generate a JSON output, but I have encountered an issue where it's creating an array of arrays with the information. What I want is to eliminate one array and simply display the list of APIs that have been used along w ...

It appears that Spring Boot is not making a custom header visible to my frontend application

Currently, I am working with a Spring Boot backend and an Angular frontend, where my goal is to enable the download functionality for a pdf file. To achieve this, I have included the following handler in my REST-controller: @GetMapping("/{id}" ...

Understanding np.argmax() in Python: a comprehensive guide

The information provided for the np.argmax() function states that it will Return the indices of the maximum values along a specified axis. The given examples are clearly outlined: In[1]: x = np.arange(6).reshape(2,3) In[2]: x Out[2]: array([[0, 1, 2], ...

Converting a string to an array: A comprehensive guide

Converting a string variable into an array: $checkedValues = $_POST['checkedValues']; The initial value of the variable $checkedValues is '257, 259, 261' Array ( [0] => 257, 259, 261 ) How can we transform this variable into an ...

Guide on toggling the visibility of two child components using *ngif in Angular 4 without losing the data

Is there a way to preserve data in my child component while using *ngIf to show and hide? I am unable to utilize the [hidden] attribute. <div id="parentcomponent"> <child1 *ngif="child1"></child1> <child2 *ngif="child2"></chi ...

Several values are not equal to the typeorem parameter

I am looking for a way to create a Typeorm query that will return results similar to the following SQL statement: SELECT * FROM Users WHERE id <> 3 and id <> 8 and id <> 23; Any suggestions on how I can achieve this? Thank you! ...

Highcharts: single point muted and not easily seen when markers are turned off

Highchart displaying data with some null points (only visible via tooltip if marker disabled): https://i.stack.imgur.com/u04v1.png https://i.stack.imgur.com/uRtob.png Enabling markers will resolve the issue of invisible points, but it may look cluttered ...