What is the most effective way to organize a collection according to the specific order specified in another array?

I have an array of objects, with each element containing another nested object like this:

data = [
  {
    name: "A",
    type: "AA",
    children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
    other: "NA"
  },
  {
    name: "B",
    type: "BB",
    children: [ { id: 2, name: "Child-B" }],
    other: "NA"
  },
  {
    name: "C",
    type: "CC",
    children: [ { id: 3, name: "Child-C" }],
    other: "NA"
  }

] 

I need to sort the entire collection by the children.id, following a specific order defined in another array:

orderArray = [3, 1, 2] 

Therefore, the desired output would be:

data =[
    {
        name: "C",
        type: "CC",
        children: [ { id: 3, name: "Child-C" }],
        other: "NA"
    },
    {
        name: "A",
        type: "AA",
        children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
        other: "NA"
    },
    {
        name: "B",
        type: "BB",
        children: [ { id: 2, name: "Child-B" }],
        other: "NA"
    }
]

Answer №1

To sort an array based on the index of children[0].id in orderArray, you can provide a comparator to Array.sort method. This comparator compares and sorts the elements accordingly.

let data = [{name:"A",type:"AA",children:[{id:1,name:"Child-A",admin:["Y"]}],other:"NA"},{name:"B",type:"BB",children:[{id:2,name:"Child-B"}],other:"NA"},{name:"C",type:"CC",children:[{id:3,name:"Child-C"}],other:"NA}];
let orderArray = [3, 1, 2];

data.sort((a,b) => orderArray.indexOf(a.children[0].id) - orderArray.indexOf(b.children[0].id));
console.log(data);

Answer №2

Check out this solution:

let updatedDataArray = []

orderArray.forEach(index => {
    updatedDataArray.push(data[index - 1])
});

data = updatedDataArray

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

Encountering an error stating "Property of undefined cannot be read" while attempting to call a function

While I can call a function without any issues, when attempting to call it within setInterval to have it run every second, an error arises: "cannot read property of undefined on the service!" constructor(private route: ActivatedRoute,private conversati ...

Is there a way to use JavaScript to retrieve a list of files that were loaded by the browser during the last request

I'm just starting out in the world of JavaScript and I have a query: is there a method to retrieve a list of files that were loaded by the browser during the last request? To clarify, when a browser loads a webpage, it not only downloads the HTML fil ...

Accessing Data from the Wikipedia API

After receiving a JSON response with the following structure: { "batchcomplete": "", "query": { "pages": { "97646": { "pageid": 97646, "ns": 0, "title": "Die Hard", "extract": "Die Hard is a 1988 ...

Creating Personalized Checkboxes for Internet Explorer Versions 7 and 8

I am currently in the process of implementing custom checkboxes for my website. Everything is functioning smoothly on browsers such as IE9 and other modern ones. However, I am encountering issues with IE8 and 7. Below is a snippet of my CSS code: input[typ ...

Are there any specialized libraries available for creating nodejs entities that mimic mysql tables?

I am looking for a solution to automatically generate entities from my MySQL schema using the Sequelize library. While I have found resources on how to do this in JavaScript, I haven't been able to find any that focus on generating TypeScript entities ...

Securing Your Angular 2 Application with UI-Router Authentication

Currently, I am working on implementing JWT authentication within my Angular 4 project. The backend setup is complete, but there are still some additional tasks to be done on the front end. During my research, I came across the auth0/angular2-jwt library. ...

Retrieving properties from a selector's output function

My situation is similar to the scenario described in the accessing react props in selectors documentation. However, in my case, let's assume that the visibilityFilter is coming from the props. Is there a way to achieve something like the following? e ...

When using Mongoose populate, it may either return an empty array or a list of Object

Currently, I am honing my skills in express.js by constructing a relational API but facing difficulty in populating keys within a schema. The structure involves having a list of properties, each with associated units. The units are linked through a proper ...

Interconnected slider and numerical entry field both influencing a shared numeric value

My goal is to display the Slider Value "sliderStatus" in a number input box that can be adjusted using various methods. For instance, if the slider is set to 199 and the customer wants to quickly select 200, they can either input the value in the box or a ...

Utilizing Knockout to Render JSON List Items

Utilizing Knockout.js to dynamically update a view from JSON response has been my current focus. The structure of the JSON is as follows: var data = { "Properties": { "Engine Capacity": "1499cc", "Doors": 3, "Extras": [ "LED lights", ...

JS receiving a reference to an undefined variable from Flask

I referenced this helpful post on Stack Overflow to transfer data from Flask to a JS file. Flask: @app.route('/') def home(): content = "Hello" return render_template('index.html', content=content) HTML <head> ...

What is the best way to loop through a JSON file using JavaScript?

Having an issue here. I need to loop through the attributes of a JSON structure, like the one shown below: var txt = '{"employees":{' + '"p1":{'+ '"info":{'+ '"firstName":"John","lastName":"Doe" }},' + & ...

It is impossible to alter the data contained within the input box

Objective: Upon clicking a button to display the modal, the selected data (first and last name) should be inserted into an input box and editable. The user should be able to modify the data. Issue: The data entered into the input box cannot be edited ...

Is it possible to assign functions to each keystroke that does not correspond to a specific keybinding in Angular?

In Angular, there are events tied to keybindings or actions like (focus), (blur), (keydown), and more. You can bind specific keybinds to certain keys as well, such as (keydown.enter), (keydown.alt), etc. Is there a method to trigger an event only when it ...

Filtering arrays based on object properties in a dynamic manner

I've created a React live search dropdown component that filters an array of objects based on a search term. It currently filters the objects by title and displays all related objects, which is working well. Current Implementation: Data Structure d ...

Is it necessary to encode the content before transmitting HTML in JSON from the server to the client?

When it comes to sending HTML content from the server to the client for displaying user comments in a rich JS app that communicates through a JSON API, there are some considerations to keep in mind. One important question is how to handle the content with ...

Transform basic text into nested JSON structure with JavaScript

There is a plain string in my possession which contains various conditions. const optionString = '{2109} AND ({2370} OR {1701} OR {2702}) AND {1234} AND ({2245} OR {2339})'; The goal is to transform this string into an object structured as foll ...

How can I create a "suggest" command using Discord.js?

How can I improve my Discord.js code for a suggest command that handles two types of suggestions - support server and bot? Currently, my code is not working as expected. Here is what I have: if (command === "suggest"){ const type = args.join(" ") ...

Increase ng-grid row height dynamically based on content without any external plugins or reliance on jQuery

I came across a similar question on this topic at Angular ng-grid row height However, none of the solutions provided there meet my requirements. If I use CSS to fix the issue, it impacts the page's responsiveness and disrupts ng-grid's header fu ...

What is the best approach to gather both the intersection and the complements of two arrays in a single operation?

Comparing Arrays - const source = [1, 1, 1, 3, 4]; const target = [1, 2, 4, 5, 6]; Initializing Arrays - const matches1 = []; const matches2 = []; const unmatches1 = []; Array Matching Process - for (const line of source) { const line2Match = target.fi ...