"Organizing an object array based on a specified order array - a step-by-step

My task involves rearranging objects within an array.

Let's assume this is the data array provided:

const data = [
  { id: 'ETHUVMY0m', name: 'item 1', value: 'value 1' },
  { id: 'McfTB40vO', name: 'item 2', value: 'value 2' }
]

There is also another array that signifies the new order:

const order = [ 'McfTB40vO', 'ETHUVMY0m' ]

In the new order, the second item needs to be moved to the first position.

Therefore, the expected outcome is as follows:

[
  { id: 'McfTB40vO', name: 'item 2', value: 'value 2' },
  { id: 'ETHUVMY0m', name: 'item 1', value: 'value 1' }
]

One approach I considered is utilizing a forEach loop:

data.forEach(d => {
  order.indexOf(d.id) // obtain the new index
  // However, I am uncertain about how to reorder the array.
})

Answer №1

Transform the data into a Map consisting of objects sorted by their id values. Then utilize Array.map() function on the order array to retrieve the corresponding item from the Map:

const data = [
  { id: 'ETHUVMY0m', name: 'item 1', value: 'value 1' },
  { id: 'McfTB40vO', name: 'item 2', value: 'value 2' }
]

const order = [ 'McfTB40vO', 'ETHUVMY0m' ]

const dataMap = new Map(data.map(o => [o.id, o]))
const result = order.map(id => dataMap.get(id))

console.log(result)

Answer №2

To achieve immutability, opt for using map and find instead of forEach:

const info = [
  { id: 'ETHUVMY0m', name: 'item 1', value: 'value 1' },
  { id: 'McfTB40vO', name: 'item 2', value: 'value 2' }
];

const sequence = [ 'McfTB40vO', 'ETHUVMY0m' ];

const output = sequence.map(id => info.find(x => x.id === id));

console.log(output);

Answer №3

You have the option to iterate through the elements in the order array:

const info = [{
    id: 'ETHUVMY0m',
    name: 'item 1',
    value: 'value 1'
  },
  {
    id: 'McfTB40vO',
    name: 'item 2',
    value: 'value 2'
  }
]

const order = ['McfTB40vO', 'ETHUVMY0m']

const result = order.map(o => info.find(({
  id
}) => o == id));

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

How can I locate and substitute a specific script line in the header using Jquery?

I need to update an outdated version of JQuery that I have no control over, as it's managed externally through a CMS and I can't make changes to it. But I want to switch to a newer version of JQuery. Here is the old code: <script type="text/ ...

Do not request for this element within the array

I have a function that applies to all elements in an array, except for the currently clicked one. For example: cubesmixed = [array, with, 145, elements] cubesmixed[54].click(function() { for(var i = 0; i < 145; i++) { var randomnumber=Math.flo ...

What is the best way to link a variable to a specific property within a

I am facing an issue with adding data from the server to a JSON property and displaying it. I know that JSON only accepts primitive types, so how can I dynamically add data to a JSON property? For instance, in the code snippet below, I am trying to assign ...

Struggling to make the JavaScript addition operator function properly

I have a button that I want to increase the data attribute by 5 every time it is clicked. However, I am struggling to achieve this and have tried multiple approaches without success. var i = 5; $(this).attr('data-count', ++i); Unfortunately, th ...

Retrieve a form (for verification purposes) from a separate AngularJS component

I'm facing an issue with accessing a form from one component to another in my project. One component contains a form, and the other has navigation buttons that, when clicked, should validate the form before moving on to the next step. However, I alway ...

Tips for creating nested maps of an array without triggering the key prop warning

I am dealing with an array of data: const arr = [ { title: "title1", content: [ { id: "home", name: "Home", }, { id: "services", name: "services", ...

The function 'create' is not a recognized property within the 'Completions' type

Recently, I've been experimenting with ChatGPT and have just installed the latest version 4.8.0. My current project is built on NextJS. Prior to this, I successfully completed a project using v3.something last month, but I'm encountering diffic ...

Encounter a critical issue while making a JSON request using Kendo UI

I am facing an issue at my workplace where I need to integrate Angular.js with ASP.NET MVC. Currently, I am trying to build a simple application that features a Kendo UI grid on the front page. In my App.js file, I am fetching data from the Data Controller ...

Exploring the possibilities of toggling between a personalized CSS design and a Bootstrap CSS layout

Is it possible to implement a dropdown menu on my sample-page using javascript/jquery in order to switch between a custom layout and a bootstrap layout? ...

What impact do the input values of an Angular reactive form have on the DOM?

I am currently working on developing a UI wizard app using Angular (reactive forms) version 6/7. The main purpose of this app is to enhance the product page of an ecommerce platform such as Shopify or WordPress. I am utilizing angular material radio inputs ...

How to Implement Button Disable Feature in jQuery When No Checkboxes Are Selected

I need help troubleshooting an issue with a disabled button when selecting checkboxes. The multicheck functionality works fine, but if I select all items and then deselect one of them, the button disables again. Can someone assist me with this problem? Be ...

Opt for employing a JavaScript variable over a JSON file

Let's start with a declaration: <div id="timeline-embed"></div> <script type="text/javascript"> var timeline_config = { width: "100%", height: "100%", debug: true, rows: 2, ...

AngularJS meta tags featuring dynamic asynchronous content

I am currently facing a challenge with my angular application that is running within a .net application. My main goal is to implement meta tags for SEO and other purposes. However, the issue I'm encountering is that I cannot determine the page title u ...

When reopening the modal in Bootstrap V5 with jQuery, the close event may not trigger as expected

When trying to implement special functionality in my modal close event using sweetalert2, I encountered an issue where the close event does not trigger again after closing the modal for the first time. Check out a live example here: https://codepen.io/th ...

Uh oh! We've encountered an issue: Unable to update headers once they have been sent

I am currently working with express and node.js My objective is to redirect users to /welcome when they visit /index and have a specific tracking code in the URL. The redirectBasedReferrer function handles the redirection based on the tracking code. inde ...

Unable to refresh JSON data in Datatables

Ensuring this operation is simple, I am following the documentation. An ajax call returns a dataset in JSON format. The table is cleared successfully, but even though data is returned according to the console statement, the table remains empty after the su ...

Using Handlebars.js to conditionally display data within an object is not functioning as expected

I am attempting to retrieve JSON data value and only display the element if the data is present. However, I am experiencing issues with Handlebar JS. var data = { listBank: [ { "enableSavedCards":"false", "enableAxisAccount":"t ...

What is preventing me from being able to use object spread results in TypeScript casting?

Uniqueness in Question My inquiry was not aimed at identifying the type or class name of an object. Rather, it delved into the concept of "casting" an object to a specific type, which arose from a misconception about TypeScript and its functionality. This ...

JSON Nesting with Ember.js and Rails

I'm currently developing a simple Ember / Rails application that involves multiple nested relationships. For instance: class Release < ActiveRecord::Base has_many :tracks end Upon accessing my Releases endpoint, I receive JSON data in the follo ...

UI-Router - templateUrl: "Ensure the content is securely delivered via HTTPS"

I am currently using HTTPS for my website. I have a requirement to send a request for templateUrl, not to a static file, but to the router: /:lang/content/library/book/:bookId Below is the setup for my state: .state('book', { url: '/ ...