Transform the event information based on specific configuration settings

I possess an array containing JSON data named config.

var config =  [ [{'state': 'step1'}],
                [{'state': 'step2'}] , 
                [{'state': 'step3'}]
              ];

The data in config is orderly arranged.

Additionally, I hold JSON data named Events, which includes these states but they are not sequential. I aim to modify the Events data based on the config.

Events: [ 
           { Status: 'rendered',  State: 'step2' },
           { Status: 'rendered',  State: 'step3' },
           { Status: 'rendered',  State: 'step1' } ,
           { Status: 'completed', State: 'step3'}  
       ],

Moreover, the final step of the config will have two entries and in that case, the rendered state should precede the completed state.

The expected outcome is as follows:

Events: [ 
            { Status: 'rendered',  State: 'step1' },
            { Status: 'rendered',  State: 'step2' },
            { Status: 'rendered',  State: 'step3' } ,
            { Status: 'completed', State: 'step3' }  
        ]

Note: I do not currently have any functional or error-prone code for this task. Essentially, I am struggling to figure out how to utilize the config to modify the Events.

Thank you

Answer №1

Reformat the config variable into a string array, and then utilize the .sort function while comparing the difference in the indexOf values of the States property within that array:

var config =  [ [{'state': 'step1'}],
        [{'state': 'step2'}] , 
        [{'state': 'step3'}]
      ];
const Events = [ 
   { Status: 'rendered',  State: 'step2' },
   { Status: 'rendered',  State: 'step3' },
   { Status: 'rendered',  State: 'step1' } ,
   { Status: 'completed', State: 'step3'}  
];

const eventOrders = config.map(([{ state }]) => state);
Events.sort((a, b) => (
  eventOrders.indexOf(a.State) - eventOrders.indexOf(b.State)
  || Events.indexOf(a) - Events.indexOf(b)
));
console.log(Events);

Answer №2

If you want to achieve this, here are the steps you need to follow:

  • Start by converting the array from the configuration, which looks like ['step1','step2','step3']
  • Proceed to use the sort() function on the events array
  • Next, sort the objects in the events array based on the indexOf() method of the State property of items in the array above

var config =  [ [{'state': 'step1'}],
                [{'state': 'step2'}] , 
                [{'state': 'step3'}]
              ];

let states = config.map(x => x[0].state);
const events = [ 
           { Status: 'rendered',  State: 'step2' },
           { Status: 'rendered',  State: 'step3' },
           { Status: 'rendered',  State: 'step1' } ,
           { Status: 'completed', State: 'step3'}  
       ]
 const res = events.sort((a,b) => states.indexOf(a.State) - states.indexOf(b.State));
 console.log(res);

Answer №3

Implemented a new logic to ensure that the status of 'rendered' comes before 'completed' if the states are the same.

var config =  [ 
    [{'state': 'step1'}],
    [{'state': 'step2'}], 
    [{'state': 'step3'}]
];

const Events = [ 
    { Status: 'rendered',  State: 'step2' },
    { Status: 'completed',  State: 'step3' },
    { Status: 'rendered',  State: 'step1' } ,
    { Status: 'rendered', State: 'step3'}  
];

const eventOrders = config.map( ([{state}]) => state);

Events.sort((a, b) => {    
    let result = eventOrders.indexOf(a.State) - eventOrders.indexOf(b.State);
    if(result == 0){
        if(a.Status=='rendered' && b.Status=='completed') return -1;
        if(b.Status=='rendered' && a.Status=='completed') return 1;
        return 0;
    }
    return result;
});

console.log(Events);

Answer №4

I've found a solution that may work for you too.

function reorganizeArray(arrToReorganize, arrToMatch, keyOfMainArray, keyOfMatchingArray) {
let reorganizedArr = [];
arrToMatch.map((val) => {
    let res = arrToReorganize.filter(obj => { return obj[keyOfMainArray] == val[0][keyOfMatchingArray] });
    res.map(r => reorganizedArr.push(r))
});
 return reorganizedArr;
}

function moveObjectToEnd(arr, key, val) {
  let lastObj = {};
  arr = arr.filter((obj) => {
    if (obj[key] == val) {
        lastObj = obj;
    }
    return obj[key] != val
 });
 arr.push(lastObj);
 return arr;
}

 let newArrangement = reorganizeArray(Events, config, 'State', 'state');
 newArrangement = moveObjectToEnd(newArrangement, 'Status', 'completed');

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

What is the best method for exporting the api call results to a csv file while ensuring that each individual response value is contained within its own

Here is the format of my API response: [ { "What time is it?": [ "option_2" ] }, { "When will we go home?": [ "option_1" ] }, { "When is your birthday?": [ "2 ...

Converting JSON data to PHP format

I am currently working with some JSON data: { 'total': 4744.134525437842, 'produksiHarian': [14.800870530853988, 15.639301040842536, 16.358413710544085, 16.952318230836113, 17.45055097248538, ...], 'r_squared': 0.9 ...

What is the best way to navigate the JSON data in order to retrieve the initial date stored within the structure?

My data is structured as a JSON object: { "col": { "2021-02-14": [ { "name": "green", "size": "large", }, { ...

Tips on obtaining JSON like the one shown below using a PHP API

I have a database table containing information on individuals with three columns: id, name, and age. There are currently four records in the table. I am attempting to create a GET API that will allow me to retrieve all of this data and return it as an arra ...

Implementing Axios interceptor is a common practice in Vue.js applications to central

Hello everyone, I'm facing a problem with the interceptor in VueJS. I can't seem to figure out where the issue lies and it's driving me crazy... I've gone through various tutorials and read numerous posts on stackoverflow, but everythi ...

What is the best way to bypass TS1192 when incorporating @types/cleave.js into my Angular application?

Using cleave.js (^1.5.2) in my Angular 6 application, along with the @types/cleave.js package (^1.4.0), I encountered a strange issue. When I run ng build to compile the application, it fails and shows the following errors: ERROR in src/app/app.component. ...

The property 'matMenuTrigger' cannot be attached to 'a' because it is not recognized

Trying to implement matMenuTrigger but encountering an error saying "Can't bind to 'matMenuTrigger' since it isn't a known property of 'a'". Any assistance would be greatly appreciated. ...

Using Jackson with runtime parameterized types

Recently relocated to Jackson and encountering difficulties deserializing JSON with a generic field. The following JSON structure needs to be parsed using Jackson: { "topic": { "headline": { ... }, "body": [ { "type": "co ...

Using JQuery to iterate through every unique div id in the HTML document

i am attempting to utilize jquery to iterate through each div tag that has an id of "rate". The goal is for jquery to execute a function on the individual divs. Here is my code snippet: information.html <html> <input class="rate" type="hidden ...

JavaScript allows for the creation of animated or timed text

Here is the code snippet I am currently working with: function list() { return "blob1<br>blob2<br>blob3"; } When I run this code, it simply displays all the text in return at once when the function is called. I am wondering if there is a ...

Incorporate external JavaScript libraries not built with Angular

Our project utilizes NPM in conjunction with Browserify for managing third-party dependencies, which pairs well with AngularJS due to the CommonJS-modules. Below is a code snippet showcasing the dependency structure that integrates seamlessly with Angular ...

Prevent rendering a file in node.js using ejs if it cannot be found

I have a specific folder structure under the views directory, containing an EJS file named profile_60113.ejs views docs profile_60113.ejs To dynamically render the file based on the groupID (where data.groupID == 60113), I use the following c ...

Retrieving the current day integer from a fullcalendar rendering in JavaScript and utilizing it as an array key

I am currently working on rendering a full calendar and I would like each cell to be displayed in a different color based on an array that contains color values for each day of the month. The array is retrieved in JSON format. Here is an example JSON arra ...

Having trouble troubleshooting C++ code in Visual Studio Code

Recently, I downloaded Visual Studio Code v1.7.1 to work on my c++ coding assignments for my degree program. While my programming skills are at a basic level, I am quite impressed with VS Code, except for one thing - I have no clue how to debug or build my ...

Unravel the JSON structure

Here is the JSON response I received from an AJAX call: [{"id":null,"period":null,"until":null,"agent_id":"15","agent_zlecajacy_id":"15","offer_id":null,"status":"1","tytul":"Pobranie ksi\u0105g","tresc":"Pobranie ksi\u0105g","data_aktualizacji" ...

Is there a way to integrate a MySQL database with parcel-bundler in a Node.js environment, or is there a simpler method to achieve this database integration with parcel-bundler?

Node.js and parcel-bundler are new to me, but I've managed to create a server.js file that connects to the database without any issues. Server.js const express = require('express'); const mysql = require('mysql'); //Establish con ...

Importing JSON data into a WPF ListBox

Exploring WPF for the first time and enjoying it, but encountering an issue. I have successfully set up a class to save and load root names and child information in JSON format. I am trying to load the JSON nickname items into a listbox when the program st ...

How to manage a particular process ID in Node.js?

I am currently working on a node application that allows clients to control a program running on the server. The program needs to run in its own terminal window at all times. Here is the ideal scenario: When a client clicks a button, a command is executed ...

How can I design a versatile button in HTML/CSS3/jQuery/Javascript that utilizes images for borders and corners for maximum scalability?

Is there a way to create a completely scalable button in HTML/CSS3/jQuery+Plugins using images for borders and corners? I have attempted a messy method, but I am confident that there are more effective solutions available. The approach I considered invol ...

The compiled JavaScript is getting messed up by the Grunt build process

I have taken over a project that was incomplete from the beginning. I am facing issues with the deployment as the grunt task is not working correctly, even after following the overrides specified here. The generated vendor.js file seems to be causing error ...