Transform array sequences into their own unique sequences

Reorder Array of List to Fit My Custom Order

Current Output:

[
    { "key": "DG Power Output", "value": "6.00", "unit": "kWh", },
    { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", },
    { "key": "Fuel Level (Before)", "value": "8.00", "unit": "liters", }
]

Convert this into

[
    { "key": "Fuel Level (Before)", "value": "8.00", "unit": "liters", },
    { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", },
    { "key": "DG Power Output", "value": "6.00", "unit": "kWh", }
]

Answer №1

To organize the items in a specific order, you can use an object to define the desired sequence and then sort the data based on the defined property.

var items = [{ title: "DG Power Output", value: "6.00", unit: "kWh" }, { title: "DG Run Time", value: "5999999952", unit: "minutes" }, { title: "Fuel Level (Before)", value: "8.00", unit: "liters" }],
    order = { "Fuel Level (Before)": 1, "DG Run Time": 2, "DG Power Output": 3 };

items.sort(({ title: itemA }, { title: itemB }) => order[itemA] - order[itemB]);

console.log(items);

Answer №2

If we were to simplify things, one method would be to directly access the index of the array like this:

let data = [
    { "key": "DG Power Output", "value": "6.00", "unit": "kWh", },
    { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", },
    { "key": "Fuel Level (Before)", "value": "8.00", "unit": "liters", }
]

Then,

let newData = [data[2], data[1], data[0]];

This approach will give you the desired output, although it comes with risks and potential errors.

Answer №3

When it comes to sorting an array, the approach usually involves creating a function that compares two elements and determines their order based on specified criteria. This function should return a number less than 0 if the first element should come before the second, 0 if they are equal, and a number greater than 0 if the second element should come first. To sort in descending order, you can utilize this function with Array.prototype.sort in the following manner:

const sorter = (a, b) => {
    if (a.key == b.key) return 0; // maintain current order
    if (a.key > b.key) return -1; // arrange 'a' before 'b' for descending order
    return 1; // arrange 'b' before 'a' for descending order
};
const arr = [
    { "key": "DG Power Output", "value": "6.00", "unit": "kWh", },
    { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", },
    { "key": "Fuel Level (Before)", "value": "8.00", "unit": "liters", }
];
console.log(arr.sort(sorter));

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

Incorporate JavaScript data into your Laravel project

I am having an issue with adding form data to a database using JavaScript. The postData is correctly being read as I can see in an alert message, but the URL is not executing. I have tried it with both 'donorlist' and '/donorlist'. $(d ...

Demonstrate the proper implementation of a Stepper component using Material UI in a React.js

I am trying to display a responsive screen using "progressive forms" with React.js and Material Ui. I have implemented the Stepper component for this purpose, but when I click the "Next Button", the button is hidden but the next step content with the text ...

Setting the UrlAction in an Asp.Net Core Controller: A step-by-step guide

There is an input box for searching on the website... The following HTML code snippet shows how the search functionality is implemented: <form id="searchForm" asp-controller="Product" asp-action="SearchProduct" method=&quo ...

The specified "ID" type variable "$userId" is being utilized in a positional context that is anticipating a "non-null ID" type

When attempting to execute a GraphQL request using the npm package graphql-request, I am exploring the use of template literals. async getCandidate(userId: number) { const query = gql` query($userId: ID){ candidate( ...

Converting a Jquery object into a Javascript object

Can someone help me decipher this piece of code? //... obj.dd.on('click', function(event){ $(this).toggleClass('active'); return false; }); //... $(function() { var dd = new DropDown( $('#dd') ); $(doc ...

Customizable mongoDB database collection

Is there a more efficient way to make calls to different collections based on a function parameter? I'm exploring the possibility and if it's not feasible, I'll handle it case by case. Currently, I have this code and the goal is to have a u ...

Dealing with errors in a sequelize ORM query: Tips and tricks

Currently, I am implementing Sequelize ORM in my Node/Express project using Typescript. Within the database, there is a 'users' table with a unique column for 'email'. As part of my development process, I am creating a signIn API and ...

Tips for selecting the best className type for material-ui components

Currently, I am integrating material-ui into a react app that is built using typescript. Within the material-ui framework, there is a feature called withStyles which allows styles to be injected into a component through its className. However, I am facing ...

A guide on utilizing the React Suite range slider in rsuite

Hello there, I recently started working with the UI framework rsuite (React suite) and everything was going smoothly until I tried to use the Range slider component's API. Unfortunately, I am facing some issues with the labels and tooltips not display ...

Encountering a Typescript issue stating "Property 'then' does not exist" while attempting to chain promises using promise-middleware and thunk

Currently, I am utilizing redux-promise-middleware alongside redux-thunk to effectively chain my promises: import { Dispatch } from 'redux'; class Actions { private static _dispatcher: Dispatch<any>; public static get dispatcher() ...

How can I create editable text using typed.js?

How can I achieve the same text animation effect on my website as seen on the homepage of ? I want to utilize the library available at . Specifically, how do I stop the animation when the text is clicked, allowing users to input their own text? Below is ...

Guide on restricting object keys to a specific set of strings in typescript

I am dealing with an API that has the ability to return one of these options: { fill: 'string'} or {stroke: 'string'} or {effect: 'string'} The key type I have established is as follows: type StyleKeyType = | 'fill&a ...

Unable to locate and interact with a concealed item in a dropdown menu using Selenium WebDriver

Snippet: <select class="select2 ddl visible select2-hidden-accessible" data-allow-clear="true" id="Step1Model_CampaignAdditionalDataTypeId" multiple="" name="Step1Model.CampaignAdditionalDataTypeId" tabindex="-1" aria-hidden="true"> <option value ...

Contrasting Compositions with Generics

Let's consider a scenario where we have an abstract class A and three concrete classes that inherit from it: A1, A2, and A3. There is also another hierarchy tree with an abstract class B and three concrete classes B1, B2, and B3. Each concrete class A ...

Ways to create distinct identifiers within a recurring function:

I am using this function twice: function (data) { $.each(data.items, function(i,item) { var $items = $('<div class="col-sm-4 grid-item"><div class="thumbnail"><input type="checkbox" name="thing_'+i+'" ...

How can I use Java Script to create animation of vertical black bars of a specific width moving across a white background?

Looking for a JavaScript code that can animate vertical black bars of a specific width moving over a white background. The desired outcome is similar to the video found at: https://www.youtube.com/watch?v=bdMWbfTMOMM. Thank you. ...

Using Jquery to trim the data returned from the server response

Utilizing asp.net for obtaining the server response via JQuery AJAX in JSON format has been my approach. I've experimented with both JQuery.getJSON() and typical jQuery response methods, followed by conversion to JSON format using $.parseJSON. Howeve ...

Determining the Clicked Button in React When Multiple Buttons are Present

Within my functional component, I have a table with rows that each contain an edit button. However, when I click on one edit button, changes are applied to all of them simultaneously. How can I identify which specific button was clicked and only apply chan ...

Execute a PHP script upon button click without the need to refresh the page

I'm facing an issue with integrating PHP and JavaScript. Objective: To execute a .php script when the event listener of the HTML button in the .js file is triggered without causing the page to reload. Expected outcome: On clicking the button, the PH ...

Is there a way to transform a tabulated tree into JSON using JavaScript?

I've been searching for a solution, but I have come to the conclusion that this question is quite peculiar. How can I convert the following text file using tabs for spacing: parent child child parent child grandchild grand ...