Arrange items according to a list of classes

How can I sort an Object with multiple properties based on a specific enum list?

Here is the Object:

const ArratOfobj = [
   { id: 3, ShortType: "LocationWorn", ImageType: "B" },
   { id: 2, ShortType: "SipStillLife", ImageType: "D" },
   { id: 1, ShortType: "SipStillWorn", ImageType: "M" },
   { id: 4, ShortType: "LocationLife", ImageType: "M" },
];

Enum Order

  const order= {
            '0': { ShortType: "SIP Still Life", ImageType: "M"},
            '1': { ShortType: "SIP Still Life", ImageType: "B" },
            '2': { ShortType: "Location Still Life", ImageType: "M" },
            '3': { ShortType: "Location Still Life", ImageType: "B" }          
        }

Expected Output

[
   { id: 2, ImageType: "D", ShortType: "SipStillLife" }, 
   { id: 4, ImageType: "M", ShortType: "LocationLife" }, 
   { id: 1, ImageType: "M", ShortType: "SipStillWorn" }, 
   { id: 3, ImageType: "B", ShortType: "LocationWorn" }
]

Answer №1

It's not possible to create an object in this manner, however, it seems like you are referring to an array of objects.

Here is a way to sort this array using an enum order:

      const ArrayOfObjects = [
          { id: 3, ShortType: "LocationWorn", ImageType: "B" },
          { id: 2, ShortType: "SipStillLife", ImageType: "D" },
          { id: 1, ShortType: "SipStillWorn", ImageType: "M" },
          { id: 4, ShortType: "LocationLife", ImageType: "M" },
        ];
        
        const enum Order {
          SipStillLife = 0,
          LocationLife = 1,
          SipStillWorn = 2,
          LocationWorn = 3,
        }
        
        const sortedArray = ArrayOfObjects.sort((a, b) => {
          return Order[a.ShortType] - Order[b.ShortType];
        });

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

Struggling to correctly showcase my Firebase data in Angular using the orderByChild method

I have a user database structured like this : Database - Users - Id (generated using the push method) - email - firstName - ptsTotal - ... I am looking to create a ranking of users based on their total points (ptsTotal) in a game using ...

Can local storage be accessed within a function and utilized during the Windows.onload event?

I have an onclick function that dynamically returns 'x' and stores it in a div. However, after a page refresh, the dynamic div resets and the data is lost. To prevent this, I stored the data in local storage within the 'test' function a ...

Access and retrieve dynamically generated table row values with the use of AngularJS

Hi, I'm new to angularjs and I have a table where I need to dynamically add rows. I've got everything working with a bit of JQuery but I'm having trouble getting the value of dynamically created table rows. Here's my code, can someone p ...

Navigating through search results on an XML page using jQuery

Context: I am currently facing a challenge involving the integration of Google search outcomes into a webpage I'm constructing. These findings are presented in XML format. My current approach to importing the XML is as follows: if (window.XMLHttpReq ...

Choose the div without a class

I currently have several divs displayed on my website. <div class="slide bx-clone"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide bx-clone"></div> <div class="slide bx-clone" ...

Leverage webpack to consolidate multiple ES6 classes into a single file for easy importing via a script tag

For the past three days, I've been grappling with webpack in an attempt to complete a simple task that could have easily been done manually. However, I am determined to learn webpack for scalability reasons... I come to you now with a desperate quest ...

Sending data from a child component to its parent counterpart

A component called cartComponent has a data property named cartCount which increases every time a new item is added to the cart. I want to utilize this value to update another value in the template that is not part of the component. Is it achievable? Bel ...

Angular (2/4) application utilizing custom-named routing within a single page architecture

I'm currently working on an Angular application that consists of a login component and a home component which serves as the main handler for the entire single page application. Additionally, I have three more components named users, each with function ...

Calculating the total of time values using Javascript

I am working with a set of time values stored as JSON data: 14:49:09 00:16:46 00:00:05 My goal is to loop through these times and calculate their sum to obtain the final total time: The resulting time will be 15:06:00 using Javascript. ...

Is it possible to bulk update a sorted set using the Redis client in Node.js?

Looking to update multiple records in a sorted set using Redis client in Node.js. Currently, I am able to update a single record with client.zAdd(key,{score:score, value:memberId}). Is there a command or function that allows for bulk updates in Redis? I se ...

What is the process for transferring a JSON data object to the server with JavaScript XMLHttpRequest?

When I attempt to send an XMLHttpRequest to a PHP server, I am encountering difficulties in getting the $_POST or $_REQUEST object to be filled with the data I am sending using JavaScript: var r = new XMLHttpRequest; r.open("POST", "http://url.com", true ...

Guide on showcasing the parameter passed in a TypeScript file on an HTML page

Just starting out with the Ionic framework and I'm attempting to show the parameter passed from the home page on my new page. I've gone through the code below but so far, nothing is showing up. Any ideas on what might be missing? Thanks in advan ...

HTML- Any suggestions on how to troubleshoot my sticky navbar not functioning properly?

I'm having trouble creating a sticky navbar. I've attempted to use z-index: 999 but it's not behaving as expected. * { margin: 0; padding: 0; } .navbar { display: flex; align-items: center; justify-items: center; position: ...

What sets apart "React.useState setter" from "this.setState" when updating state?

After clicking on the button in AppFunctional, the component fails to update even though the state has changed. However, everything works fine in AppClass. In both cases, we are mutating the original state with "push", but I'm struggling to understan ...

An easy way to pass props to a component using useNavigate in React Router

Is it possible to send props directly to a component in React? const goToProjectPage = useNavigate(); useEffect(()=>{ ..... goToProjectPage("/projectpage"); //send props here },[]); ...

Tips for extending an array to a different length while maintaining the original distribution of values

Assuming I have a numpy array of length n represented as follows: [2.456970453262329, 2.3738574981689453,... 1.28790283203125,] If the goal is to "stretch" this array to have a length of m (where m>n) while maintaining the general distribution ...

Differences Between Angular 2 Reactive Forms and Template Forms

We are embarking on a new Angular 2 project and are deliberating on whether to opt for Reactive Forms or Template Forms. If you want to learn more, you can refer to this article: https://angular.io/guide/reactive-forms From what I understand, the main adv ...

How can I dynamically apply an active class when clicking on a group of buttons?

Iterating through the buttons array, I retrieve three buttons. My goal is to determine which button has been clicked and apply an active class to it. import React from "react"; import { useState } from "react"; import style from "./years.module.scss"; co ...

How can datatables format a column by pulling from various sources? (Utilizing server side processing

Struggling to implement server-side processing with concatenated columns and encountering SQL errors. Came across a post discussing the issue: Datatables - Server-side processing - DB column merging Would like to insert a space between fields, is this ac ...

Ways to boost an array index in JavaScript

I recently developed a JavaScript function that involves defining an array and then appending the values of that array to an HTML table. However, I am facing an issue with increasing the array index dynamically. <script src="https://cdnjs.cloudflare. ...