Tips for synchronizing the indexes of two arrays using a common value in JavaScript

Is there a way to sort one array to match the order of another array with identical content, based on a shared property?

For instance:

let firstArray = [{id: 123, ...}, {id: 456, ...}, {id: 789, ...}] // always in this order
let secondArray = [{id: 456, ...}, {id: 789, ...}, {id: 123, ...}] // always different order

I want to rearrange firstArray so that:

firstArray[0].id is 456 and secondArray[0].id is 456

Answer №1

Iterate through the initial array and transfer items to the second array based on their index:

let initialArr = [{id: 111}, {id: 222}, {id: 333}] // maintain original order
let finalArr = [{id: 222}, {id: 333}, {id: 111}] 

initialArr.forEach((object, index) => {
  finalArr[index] = object
})

console.log(initialArr, finalArr)

Answer №2

To organize the objects we need from array2 based on the specified order in array1, we can map over the ordering array and use it to select the desired objects...

let array1 = [{id: 123 }, {id: 456 }, {id: 789, }]
let array2 = [{id: 456, name: '456' }, {id: 789, name: '789' }, {id: 123, name: '123' }]

let array2ElementsSortedByArray1 = array1.map(e => {
  return array2.find(e2 => e2.id === e.id)
})

console.log(array2ElementsSortedByArray1)

Answer №3

To streamline the ordering process of elements in array1, one strategy is to generate a hash with the structure {id: index, ...} based on the values in array2. By doing so, you eliminate the need for using find() during each iteration.

let array1 = [{ id: 123, }, { id: 456, }, { id: 789, }] // order always stays the same
let array2 = [{ id: 456, }, { id: 789, }, { id: 123, }]

const
  indeces = Object.fromEntries(array2.map(({ id }, i) => [id, i])), // { 456: 0, 789: 1, 123: 2 }
  ordered = [];
array1.forEach(o => ordered[indeces[o.id]] = { ...o });

console.log(ordered)

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

Alert triggers a transformation in the background

Can someone help me figure out this issue? https://jsfiddle.net/eddnhc5f/ I've noticed that when I press the key c on Firefox and Microsoft Edge, the background changes before the alert pops up. However, in Opera and Chrome, the background changes a ...

Creating a unique-looking visual representation of progress with arcs

Looking to create a circular progress bar (see image below), with loading starting from the left bottom side up to the right bottom side. The empty state should be light-blue (#E8F6FD) and the progress color strong blue (#1CADEB). https://i.sstatic.net/VZ ...

Utilize a Web Api controller to authenticate and verify the data input in

Currently, I am working on a web API application that includes the following form: <form id="editForm"> <input id="editid" type="hidden" name="id" /> <p><label>Numéro cnss </label&g ...

Display the element when the input is in focus

I'm currently working on optimizing a code snippet. The idea is to display a paragraph tag showing the characters remaining when you focus on a textarea. Here's what I have so far: import React, { Component } from "react"; class Idea extends Co ...

displayEvent not functioning properly within fullcalendar

I'm attempting to add an event to FullCalendar.io using a JavaScript function. I've tried two methods. Triggering the function at the end of the page or by clicking. No error is displayed, but the event isn't showing up on my calendar. & ...

Send your information without having to navigate away from the current

This is my form <form id="reservationForm" action="sendmail.php" method="post"> ... . . . . <input type="image" src="images/res-button.png" alt="Submit" class="submit" width="251" height="51px"> Here is my javascript $("#reservationForm").su ...

Accessing the value returned by an asynchronous function in Node.js with Electron

As I embark on a new project, my goal is to take user input, process it through a function, and then return the updated value back to the user. Despite being a novice with async functions, I've done extensive research but still can't pinpoint if ...

Encountered a module build failure due to the inability to resolve the 'bootstrap-sass' module, a required installation when configuring bootstrap version v3

Encountered an error while building an angular project: ERROR in ./~/bootstrap-loader/lib/bootstrap.loader.js!./~/bootstrap-loader/no-op.js Module build failed: Error: Could not resolve module 'bootstrap-sass' which must be installed when bootstr ...

Significant slowdown observed when deleting multiple objects from the Three.js scene

We are facing a challenge when dealing with large Three.js scenes that consist of many individual objects. In some cases, our scenes can contain anywhere from 25,000 to 50,000 instances of Object3D. While this may seem like a lot, we haven't found an ...

How to efficiently store data using ajax and php techniques

I'm currently working on sending data via ajax for the user_question and language input fields. Can anyone help me with the correct way to include this element in the ajax JavaScript code so that I can save the table element value in my database? Tha ...

Change element position to relative while scrolling

I created a wrapper with an animation similar to the one on Apple's Airpods Pro page. It features a video that plays gradually as I scroll, with the text smoothly scrolling over it within a specific area (text-display). So far, this part is working w ...

Simple guide on converting a JavaScript object into JSON

I am currently facing a challenge in converting the following JavaScript object into valid JSON format: [{ '"Sno"': '"1"', '"Purchase Date Time"': '"2017-11-14 14:09:32"', '"Txn Type"': '"COD"&apo ...

Posting a JavaScript string to a C# backend in ASP.NET Core MVC: A step-by-step guide

I am a beginner in ASP and facing an issue while attempting to pass a string from my JavaScript code to my controller. The intention is to utilize this string for querying my database. JavaScript function findEmployees(userCounty) { $.ajax({ t ...

What is the best way to show a tooltip alongside highlighted text?

How can I display a tooltip (using qTip) next to selected text? The code below captures the selected text in the console, but the tooltip is not displayed. <div class='test'>Actual text will be much longer...Test Test Test Test Test Test T ...

Accessing process.env in Nest.js controllers

Is there a way for me to access process.env.SOME_FIELD in nest.js? app.module.ts ... modules: [ ... ConfigModule.forRoot({ envFilePath: '.env.' + process.env.APP_CODE }), CatModule ... ] ... CatController.ts ...

Exploring the array feature in Google Sheets' sequence function

Within my table, one column displays Initial Year while another shows the number of amortisation years for each entry. My goal is to create a new table where rows are duplicated when the number of amortisation years is greater than 1, with the Year recalcu ...

Is there a way to retrieve a button element from a pug template?

Why can't I use a button in index.js from a pug template? Here is the code in my pug template: doctype html html head meta(charset='UTF-8') meta(http-equiv='X-UA-Compatible' content='IE=edge') meta(name=& ...

The unique identifier for retrieving an object from the database is dynamic and subject to change with each

Click here for image description I am currently building an app using Express and Mongoose MongoDB. However, when I try to access /musics/:id to go to the details page, the app redirects me to the correct page but crashes because the id is being changed. ...

Issue with displaying bar and line charts in ChartJS

I am currently working on an HTML report that includes numerous charts. While each chart is functioning properly, I have encountered an issue with one specific chart - Surface Solar Radiation and Sunshine. Despite my efforts to debug and identify the probl ...

An error occurred when trying to pass JSON data to the view in the "orchard" framework: TypeError - e.slice is not a function

public ActionResult Grouping() { return View(); } public ActionResult Read([DataSourceRequest] DataSourceRequest request, string text) { var result = _auto.Table.ToList().Where(s => s. ...