Arranging an array of objects according to the specified property in a consistent format

In order to sort an array of objects by a specific property with the following criteria: - The first item must be either Camel or Absolute. - The second item must be Dream. - The third item must be Carnival.

[Camel, Dream, Carnival] or [Absolute,  Dream, Carnival]

For Example 1:

 var items = [
     { 'Name':'Carnival', 'TypeId':3, ... },
     { 'Name':'Camel', 'TypeId':55, ... },
    { 'Name':'Dream', 'TypeId':4 , ...},
    ]

The expected result is:

var itemsSorted = [{ 'Name':'Camel', 'TypeId':55, ... },
    { 'Name':'Dream', 'TypeId':4, ... },
    { 'Name':'Carnival', 'TypeId':3, ... }]

For Example 2:

   var items = [
     { 'Name':'Carnival', 'TypeId':3, ... },
    { 'Name':'Dream', 'TypeId':4 , ...},
    { 'Name':'Absolute', 'TypeId':114 , ...}]

The expected result is:

   var itemsSorted = [{ 'Name':'Absolute', 'TypeId':114, ... },
    { 'Name':'Dream', 'TypeId':4, ... },
     { 'Name':'Carnival', 'TypeId':3, ... }]

I have implemented a solution that works based on these criteria. However, I am open to suggestions for a more elegant approach. Any recommendations?

private _setUpdateProgress() {
   const order = ['Camel', 'Absolute', 'Dream', 'Carnival'];
   this.itemsSorted = [];

   if (this.items?.length) {
      for (let i = 0; i < order.length; i++) {
        if (i === 1) {
          continue;
        }
        let info!: Array<any>;
        if (i === 0) {
          info = items.filter(x => x.Name === 
              order[0] || x.Name === order[1]);
        }
        if (i > 1) {
          info = items.filter(x => x.Name=== 
              order[i]);
        }
        this.itemsSorted.push(info[0]);
     }
    }

Answer №1

To efficiently organize these strings, you can create an object for mapping each string to a specific number. Then, utilize the sort function to compare these numbers:

const order = { "Apple": 1, "Banana": 2, "Cherry": 3, "Date": 4 };

const customSort = arr => arr.sort((a, b) => order[a.Fruit] - order[b.Fruit]); 

// Sample scenarios
var fruits = [
    { 'Fruit':'Cherry', 'Quantity':25 },
    { 'Fruit':'Apple', 'Quantity':55 },
    { 'Fruit':'Date', 'Quantity':34 },
];
console.log(customSort(fruits));

fruits = [
    { 'Fruit':'Cherry', 'Quantity':10 },
    { 'Fruit':'Date', 'Quantity':29 },
    { 'Fruit':'Banana', 'Quantity':42 },
];
console.log(customSort(fruits));

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

Converting an array of objects into a TypeScript dictionary with IDs as the key mapping

Is there a way to provide type hints for better autocompletion when accessing keys like dictionary.Germany from the following data and types? type Entry = { tld: string; name: string; population: number; }; const data: Entry[] = [ {tld: 'de&a ...

Struggling to get the bindings to work in my Angular 2 single-page application template project

I have recently started using the latest SPA template within Visual Studio 2017: https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp.net-core-with-javascriptservices/ The template project is functioning properly. ...

Unable to locate a variation for 'subscript' that can accept the given arguments

func handleKeyboardNotification(notification:NSNotification) { var data = notification.userInfo var keyboardSize: CGFloat = (data[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue().size.height adjustScrollViewBottomConstraint.constant ...

Sass Alert: The mixin called roboto-family is missing from the stylesheet. Trace: Problem detected in src/pages/forms/forms.scss at

Greetings, I am diving into the world of Ionic for the first time. Recently, I embarked on a new project in Ionic and decided to integrate a theme. To do so, I copied an .html file, an .scss file, and also created a .ts file. Forms.html <!DOCTYPE html ...

What causes a React Native wrapped component to re-render consistently?

I have a functional component in React native (expo) that is displaying a page using the stack navigator. On this page, there is a simple color picker (react-native-wheel-color-picker), which is a native component, and a button that updates the state. I&a ...

Restrict the prop in Typescript to only accept a specific element

Is there a way to restrict the type of elements passed as props to a component? For example, I want a prop called divider in my component that only allows <svg> elements to be passed. import { ElementType, ReactElement } from 'react'; typ ...

The issue of footer overlapping the login form is observed on iOS devices while using Safari and Chrome

Unique ImageI am currently working on an Angular 8 project with Angular Material. I have successfully designed a fully functional login page. However, I am encountering a problem specifically on iOS devices such as iPhones and iPads, whether it is Safari o ...

Utilizing a Typescript class interface does not maintain the original method types

Struggling to define a Typescript interface and implement it in a class. The issue lies in the method signatures of the interface not being applied to the class as expected. Below is a simplified example: export interface Foo { bar(value: string): voi ...

Utilizing the useSearchParams() function to retrieve live data in Next.js

Is there anyone who has successfully migrated from the pages router to the app router in Next.js? I am facing an issue with dynamic data migration. In the pages router, dynamic data is retrieved on a page using useRouter().query, but in the app router, it ...

Is there a way to clear a client's browser local storage, session storage, and cache without requiring them to log out?

We make use of local storage, session storage, and cache to store data actively. We maintain this data until the user chooses to logout, without forcing them out. However, we face a challenge when it comes to replacing old data with new data in the cache a ...

Error message "After the upgrade to Angular 15, the property 'selectedIndex' is not recognized in the type 'AppComponent'."

My Ionic 6 app with capacitor has been updated in the package.json file. These are the changes: "dependencies": { "@angular/common": "^15.1.0", "@angular/core": "^15.1.0", "@angular/forms": "^15.1.0", "@angular/platform-browser": "^15.1. ...

What causes the website to malfunction when I refresh the page?

I utilized a Fuse template to construct my angular project. However, upon reloading the page, I encountered broken website elements. The error message displayed is as follows: Server Error 404 - File or directory not found. The resource you are looking fo ...

Can a TypeScript interface inherit from multiple other interfaces simultaneously?

Hello Angular Community, I have a question regarding nesting three interfaces within another interface. Let me explain with some code: I am attempting to integrate the IProject1, IProject2, and IProject3 interfaces into the IAdmin2 interface: Thank you ...

Retrieve an array of specific column values from an array of objects using Typescript

How can I extract an array from an array of objects? Data var result1 = [ {id:1, name:'Sandra', type:'user', username:'sandra'}, {id:2, name:'John', type:'admin', username:'johnny2'}, ...

ng-repeat table grouping by date

How can I utilize *ngFor to generate an HTML table grouped by date in columns? Here is an example of a JSON List: [{ "id": "700", "FamilyDesc": "MERCEDES", "model": "Mercedes-BenzClasse A", " ...

Updating AngularJS variable information through queries

My code requires frequent updates to a variable named $user. I am contemplating whether to send a query to the server every x seconds (which includes userdata) or if it's feasible to update it on every other POST request I make using AngularJS. Coul ...

Can TypeScript restrict a callback parameter based on the type of another parameter using generics?

I am currently developing an event manager system. The main objective is to allow users to subscribe to events by providing an event type and a callback function. In my implementation, events are represented as classes, where AwesomeEventType in the exampl ...

Add the item to the array and then use the *ngFor directive to iterate

Whenever the addRoom button is clicked, I want to add an object to an array. The problem is that the data in my array keeps getting repeated. Please excuse any language errors in my explanation. Feel free to ask me for clarification in the comments below. ...

While utilizing the imodel.js front-end for designing a custom geometric model, I ran into an issue while trying to display it

Utilizing imodel.js front-end, I was able to design a customized geometric model featuring elements like a collection box. However, when placing the model within the existing SpatialViewState in bim, it failed to display properly in the current view. Sub ...

Encountering an Angular 2 npm installation issue: (node:3240)

Seeking assistance with setting up a MEAN 2.0 example from this GitHub repository. After successfully running npm install on the server folder, encountering issues when executing npm install on the client folder (Angular 2), resulting in the following err ...