Arrange a static array of objects by leveraging a separate array

I have a variable that sets the order of objects in a specific way:

const order = ['large', 'medium', 'small'];

My goal is to arrange the data array objects according to the names specified in the order array:

const data = [{name: "small", children: []}, {name: "medium", children: []}, {name: "large", children: []}]

The desired outcome would be:

const data = [{name: "large", children: []}, {name: "medium", children: []}, {name: "small", children: []}]

Can someone help me achieve this sorting?

Answer №1

To achieve this, we utilize the index position of the name within the order array:

const order = ['large', 'medium', 'small'];
const data = [{name: "small", children: []}, {name: "medium", children: []}, {name: "large", children: []}];

const sortArray = (arr, order) => {
  return data.sort((a, b) => order.indexOf(a.name) - order.indexOf(b.name)); 
}
console.log(sortArray(data, order));

Answer №2

utilizing the lodash library

_(data).orderBy([(x) => {
    return sequence.findIndex(y => y.name === x.name);
}]).value();

Answer №3

Here is my recommendation:

data  = data.sort(item => order.indexOf(item.name))

Alternatively, you could try:

data  = data.sort(item => -order.indexOf(item.name))

Answer №4

To achieve a custom sorting of elements based on a predefined order array, you can create a sort function that compares the index of the matched word.

Here's an example:

const order = ['red', 'green', 'blue'];
const data = [{color: "blue", value: 10}, {color: "red", value: 5}, {color: "green", value: 7}];

const sortedData = data.sort((a, b) => order.indexOf(a.color) - order.indexOf(b.color));

console.log(sortedData);

Answer №5

To improve efficiency when dealing with large arrays, it's best to avoid scanning in each call of the sorting callback function as this can lead to a time complexity of O(n²logn). Instead, consider converting the order information into a map (such as a plain object) and utilizing bucket sort for a linear time solution:

const order = ['large', 'medium', 'small'];
const data = [{name: "small", children: []}, {name: "medium", children: []}, {name: "large", children: []}];


// Preprocessing step O(n)    
const map = Object.fromEntries(order.map((key, i) => [key, i]));
let result = order.map(() => []);
// Bucket sort step O(n)
for (let obj of data) result[map[obj.name]].push(obj);
// Flattening step O(n)
result = result.flat();
console.log(result);

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

Retrieving row and column values from an 81-element indexed array

I am working with an indexed JavaScript array that contains exactly 81 elements. These elements will form a 9x9 grid, similar to a Sudoku puzzle. Right now, I am trying to figure out the most efficient way to extract row and column values from this array. ...

Ways to extract link value in Angular

Is there a way to extract a value from a link using Angular 4? I have used *ngIf and would like to display a div based on the value within the link. <div *ngIf="obtain the value from the current href"> ...

Why isn't PHP json_encode properly encoding data?

Here is an example of the array structure stored in $arrayResult: array (size=1) 'Records' => array (size=1498) 0 => array (size=4) 'code' => string '9999999' (length=12) &ap ...

Why is it important to refuse cookies on websites?

On my website, I have a button for users to decline cookies. If they choose to decline cookies, Google Analytics will not be functional on the site due to the code that has been set up. I have noticed that some other websites offer options in their cookie ...

How to align an unordered list vertically in the center using Bootstrap?

Trying to figure out why the ul within this parent div is not centered vertically. Here is a screenshot of the issue: https://i.sstatic.net/ZOc9M.png <div className=" d-flex align-items-center bg-primary "> <ul ...

"Discovering the magic behind leaflet js's method of fetching tiles directly from

If you imagine tiles being stored in a file system similar to the image shown below https://i.sstatic.net/6NryK.png You can take a quick look at this URL Take a look at the code var map = L.map('map').setView([0, 0], 2); L.tileLayer(& ...

What is the process for retrieving information from a database in Django when the submit button is clicked?

Is there a way to retrieve database objects in HTML only when the submit button is clicked, instead of loading them automatically on page load? Currently, I have an AJAX script running on a form that displays text entered in a textbox onto the HTML when th ...

Identify mesh interaction on a 3D model

I have successfully loaded a model in from .obj and .mtl files. My goal is to allow the user to interact with specific parts of the model, such as changing their color by clicking on them. For example, clicking on a door of a car should enable the user to ...

Node.js is much more than just wrong

Hey there, I have a Node.js issue that's giving me some trouble. Take a look at my code and the output below to see if you can help: if (currentPrice > variableData[i].stopLossHard) { console.log('if') console.log(currentPrice) ...

Transform a dynamic web page into a static one using Next.js

Utilizing Next.js and React.js, I create dynamic web pages. Specifically, I generate user-related web pages that need to be updated when there are changes in the user data. How can I generate static HTML pages from this updated data within Next.js? Are the ...

What steps can be taken to ensure that only a single decimal separator is included?

I've created a calculator in HTML with two display screens, operators, and number buttons. The challenge I'm facing is implementing a decimal separator. Initially, I attempted to use a boolean variable as a switch, but the number() function remov ...

Issue with React submit button for posting data is not functioning as intended

My dilemma lies within a Modal component containing a Form and Button. The goal is to trigger a POST request (managed in a separate file) upon the user clicking the button, which will run a simulation using the validated input values. Surprisingly, the onC ...

Leverage the power of Fluentlenium to effortlessly upload a file using dropzone.js

Currently, I am trying to create a test for file uploading using Fluentlenium and DropZone.js (). Dropzone.js operates within a modal where users can drag and drop files or upload them traditionally. However, the test crashes as soon as the upload button ...

A hyperlink unveils a visual and conceals its own presence

I'm a beginner in the world of coding and I have a question about creating a link that reveals a hidden image while hiding itself using HTML. After some research, this is what I've come up with: <a href="javascript: ...

Keep Modal Open During Ajax Requests

After clicking the edit button and making changes to the form, I want to reset the page background. However, when I click edit, the form is edited and the modal closes but does not completely close. The div ajaxshow is a layout element that displays the a ...

Utilizing Bluebird promises with ES6 object methods

Currently, I am working with node v0.11.14-nightly-20140819-pre on a Windows system where the harmony flag is activated. Within my JavaScript code, there is an object that contains two methods defined in its prototype: function User (args) { this.ser ...

When the Ionic framework is initialized, it automatically redirects users to the home

I'm currently developing a mobile app using Ionic, and I've encountered an unusual issue. Whenever I refresh the page (pressing F5) from a specific route like "/tabs/connected/channel/edit", I always get redirected to "/tabs/home" after the state ...

Text field suddenly loses focus upon entering a single character

In my current code, I have functions that determine whether to display a TextField or a Select component based on a JSON value being Text or Select. However, I am facing an issue where I can only enter one letter into the TextField before losing focus. Sub ...

Using incrementing CSS IDs to implement multiple modal windows on a single webpage

I am faced with a dilemma where I have more than eight modals on a single page, each having a unique CSS id. Initially, I had a JavaScript code snippet that worked perfectly for a sole modal, but it failed to target all the different CSS ids. As someone ...

Passing the value selected from a datepicker to PHP without refreshing the page through the use of XMLHttpRequest: Guide

Is it possible to transfer the datepicker value to PHP without reloading the HTML page by using XMLHttpRequest()? The intention is to utilize this date value for a subsequent query and present it on the same HTML page. <input type="date" id="month" o ...