Arranging a collection of objects in alphabetical order

My current challenge involves sorting an array of objects alphabetically, and to simplify things, I have provided the example below. In my TypeScript code, I utilize splice to add and remove items from the object array.

Array

  cars = [{
        id: 1,
        items: [{
          name: 'car1',
          description: 'this is car1 description'
        },{
          name: 'car2',
          description: 'this is car2 description'
        },{
          name: 'car3',
          description: 'this is car3 description'
        },{
          name: 'car4',
          description: 'this is car4 description'
        },{
          name: 'car5',
          description: 'this is car5 description'
        }]
   }];

html

<p-dataView [value]="cars" [paginator]="true" [rows]="5">
  <p-header>List of Cars</p-header>
  <p-footer>Choose from the list.</p-footer>
  <ng-template let-car pTemplate="listItem">
      <p-fieldset legend="Header" *ngIf="car.id === 1" [toggleable]="true">
          <div *ngFor="let _car of car.items">
              {{_car.name}} - {{_car.description}}
          </div>
      </p-fieldset>
  </ng-template>
</p-dataView>

**********************************************UPDATE******************************** I apologize for the oversight, there is one more layer within the structure.

  cars = [{
        id: 1,
        items: [{
             Model:[{  
                        name: 'car1',
                        description: 'this is car1 description'
                   }],
             Model:[{  
                        name: 'car2',
                        description: 'this is car2 description'
                   }],

        },
           id:2,
            items: [{

               Model:[{  
                        name: 'car13,
                        description: 'this is car3 description'
                   }],
             Model:[{  
                        name: 'car4',
                        description: 'this is car4 description'
                   }],
        }]
   }];

I attempted

cars[0].items.Model.sort((a,b) => a[0].name > b[0].name ? 1 : -1) //It did not work

also tried

cars[0].items.Model.sort(function (a, b) {
                var nameA = a.name.toLowerCase();
                var nameB = b.name.toLowerCase();
                if (nameA < nameB) //sort string ascending
                    return -1
            })

Answer №1

vehicles = [{
        id: 1,
        parts: [{
          name: 'engine',
          info: 'this is engine description'
        },{
          name: 'tires',
          info: 'this is tires description'
        },{
          name: 'brakes',
          info: 'this is brakes description'
        },{
          name: 'lights',
          info: 'this is lights description'
        },{
         name: 'battery',
          info: 'this is battery description'
        }]
   }];

  vehicles[0].parts.sort((a,b) => a.name > b.name ? 1 : -1)

Answer №2

We could also opt for a more concise version:

 vehicles[0].parts.sort((x,y) => x.title.localeCompare(y.title))

Answer №3

If you're looking to streamline your code, consider utilizing a library like Underscore.js for handy utility functions:

Underscore.js, particularly the sortBy method.

To incorporate Underscore.js into your project, simply import it into your component:

import * as _ from 'underscore';

Next, utilize the sort method by passing in the array of objects and the key to sort by:

_.sortBy(car.items, 'name');

If you make any changes to the car array, remember to update the car.items collection by resorting it:

car.items = _.sortBy(car.items, 'name');

You can now display your data with confidence, knowing it's sorted correctly.

Answer №4

Simple sorting method using Array.prototype.sort()

cars.sort(function(a,b) {
  if (a.items.name < b.items.name) return -1;
  if (a.items.name > b.items.name) return 1;
  return 0;
})

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

Is it possible for a Firestore query using .where() to conduct a search with no results?

Currently, I am in the process of creating a platform where users can upload past exams. Each document contains various fields such as teacher, year, and class, all stored in cloud Firestore. To filter the data by teacher, I am using the .where("Teacher" ...

Error: The StsConfigLoader provider is not found! MSAL angular

I am currently using Auth0 to manage users in my Angular application, but I want to switch to Azure Identity by utilizing @azure/msal-angular. To make this change, I removed the AuthModule from my app.module and replaced it with MsalModule. However, I enco ...

Angular Space-Friendly Table

After attempting to code the sample in Angular, I realized it wasn't what I was looking for. <table> <th >Number</th> <th >Merchant Name</th> ...

Angular 2: Issue with disabled functionality not functioning correctly

In my TypeScript code, I have created a boolean variable called readOnlyMode. When this variable is set to true, all elements should be disabled. To achieve this, I am using [disabled]="readOnlyMode" in the HTML for elements that need to be disabled. Howev ...

Encountering an error from the Angular CLI compiler can be frustrating, but fear not! By making a simple change (that can always

When I was compiling my app for the first time using ng serve I encountered this error: img error However, when I made a change to one of the comp files (it could be any file), and webpack recompiled it with Angular CLI - everything worked fine. I sus ...

Carousel-item height in Bootstrap 4.6

I am facing an issue with a component in Angular 14 using Bootstrap v4.6: <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div cl ...

Decoding enum interface attribute from response object in Angular 4 using typescript

From an API response, I am receiving an enum value represented as a string. This enum value is part of a typescript interface. Issue: Upon receiving the response, the TypeScript interface stores the value as a string, making it unusable directly as an en ...

Parsing JSON using dotted paths in Python

Are there any Python libraries available on PyPI that allow me to parse JSON using dot-separated paths and order-independent arrays? 1. dot separated path 2. order independant in case of array Data : "attr1": [ { "attr2": "val2" }, ...

Issue with react-native-svg ForeignObject missing in project (React Native with Expo using TypeScript)

I am working on a React Native project in Expo and have incorporated the expo TypeScript configuration. Using "expo install," I added react-native-svg version 9.13.3 to my project. However, every time I attempt to render the SVG using react-native-svg, I ...

JavaScript is failing to add items to an array

Attempting to add coordinates and user-specified data from a form to an array named "seatsArray". Here's the code snippet: <div> <img onLoad="shiftzoom.add(this,{showcoords:true,relativecoords:true,zoom:100});" id="image" src="plan1.bmp" wid ...

Using MUI DatePicker and react-hook-form to implement a date picker in the format DD/MM/YYYY

I have developed a custom datePicker component that combines react-hook-form and Material UI. However, I am encountering an issue where the values are being displayed in the format: "2024-04-10T22:00:00.000Z" Below is the code snippet: import { Localizati ...

Create the Smallest Possible Number by Eliminating n Digits from a Specified Number

In this algorithm, a number (as a string) is input and the goal is to remove n numbers in order to obtain the lowest possible resulting number. It's important to maintain the original order of the numbers while removing them. To achieve an O(n) effic ...

Models in Typescript that are interrelated with Loopback

I'm currently working on defining connected models including the HasMany relationship in the context of @types/loopback definitions My approach involves creating an interface for HasMany and its implementation: interface IHasMany { /** ...

Issue in Vue.js where arrays are disappearing after being updated in a mutation

I'm encountering an issue with my project, which is similar to stackoverflow in the sense that it involves asking and answering questions. When I click on the up or down button to indicate whether a solution is useful or not, the data is sent to the b ...

Is there a way to manipulate arrays into slices within a match clause?

I have a situation where I have an enum with variants that contain arrays of different lengths. When attempting to use a `match` statement on this enum: enum EnumArray { One([i32; 1]), Two([i32; 2]), } fn main() { let arr = EnumArray::One([1] ...

Import a Component Dynamically Using a Variable in AngularJS

I am attempting to dynamically load a component using a variable, but I keep running into an "Uncaught Error: Template parse errors". How can I achieve this successfully? <app-{{ this.plugin.component }}></app-{{ this.plugin.component }}> ...

Holding off on completing a task until the outcomes of two parallel API requests are received

Upon page load, I have two asynchronous API calls that need to be completed before I can calculate the percentage change of their returned values. To ensure both APIs have been called successfully and the total variables are populated, I am currently using ...

What is the best way to ensure a specific row remains at the bottom of an Angular table with Material when sorting?

My data table contains a list of items with a row at the end showing the totals. | name | value1 | value2 | --------------------------- | Emily | 3 | 5 | | Finn | 4 | 6 | | Grace | 1 | 3 | | TOTAL | 8 | 14 | I&apos ...

Guide on deploying a Node.js and Angular application on Google Cloud Platform

I currently have a setup where both my nodejs backend and angular frontend app are located in the same directory. The angular app generates build files in a static folder, and the nodejs backend serves the HTML file using the following code snippet: //Exp ...

Guide on integrating an element into a different element in a Vue 3 Tree Viewer

In my current setup, I've implemented a TreeView component that holds a tree. Each tree entry includes Children with their own unique label, perm, and further children. Take a look at an example of the tree: App.vue let tree = ref({ label: 'o ...