Most efficient method for comparing two JSON arrays and rearranging their positions

I am faced with a challenge involving two Javascript JSON arrays. The arrays in question are named this.BicyclePartsOLD and this.BicyclePartsNEW.

Both arrays contain an attribute named "ListOrder". The OLD array is currently ordered from ListOrder 1 to n items.

The NEW array has been modified but still contains the same records as the BicyclePartsOLD. Now, I need to update the OLD array based on changes made in the NEW array. For example, if someone changed the ListOrder from 1 to 3 in the NEW array, I need to update the OLD array accordingly by setting ListOrder 1 to 3, ListOrder 2 to 1, and ListOrder 3 to 2.

I have attempted the following approach, but I am unsure about the best way to rearrange the ListOrder values:

for(var i = 0; i < this.BicyclePartsOLD.length; i++)
{
     for(var j = 0; j < this.BicyclePartsNEW.length; j++)
     {
          if(this.BicyclePartsOLD[i].PartNumber === this.BicyclePartsNEW[j].PartNumber)
          {
              this.BicyclePartsOLD[i].ListOrder = this.BicyclePartsNEW[j].ListOrder;
              //NOT Sure how to reorder BicyclePartsOLD here, there will be another
              //item with the same ListOrder at this point.
          }
     }
}

If anyone could provide guidance or advice to help me navigate towards the right solution, it would be greatly appreciated.

Answer №1

Instead of having two separate arrays with identical data but unrelated objects, why not consider creating two arrays that both contain the same objects? This way, making changes to an object will automatically be reflected in both places.

One approach is to have two arrays pointing to the same objects:

Array1 -> [{foo:'bar'},{baz:'bam'}]
Array2 -> [{baz:'bam'},{foo:'bar'}]

The object containing 'foo' in the first array can be the exact same object as the one with 'foo' in the second array (not just similar properties). Editing one will result in changes being mirrored in both arrays.

For this purpose, you could use a slice() on the NEW array to create a copy of the array at one level deep. Essentially, it's the duplicate items in a different container array. You can then sort the newly sliced array as desired.

this.BicyclePartsOLD = this.BicyclePartsNEW.slice().sort(function(){...});

To avoid repetitive slicing, it's recommended to create both OLD and NEW arrays initially. When adding an entry, generate an object with your data and push that object into both arrays, ensuring they hold the same object for synchronized editing.

Consider something like this:

var OLD = [];
var NEW = [];

// Adding an entry
var newItem = {}
OLD.push(newItem);
NEW.push(newItem);

//Editing that item should apply to both arrays since they share the same object
OLD[0].someProperty = 'someValue';

console.log(OLD[0].someProperty); // someValue
console.log(NEW[0].someProperty); // someValue


// An item exclusive to OLD
var oldItem = {};
OLD.push(oldItem);

// Another item only in OLD
var yetAnotherOldItem = {};
OLD.push(yetAnotherOldItem);

// Moving one of those old items to NEW and making edits to it
NEW.push(OLD[2]);
OLD[2].revived = 'I feel new!';

// The changes should reflect in both arrays, although at different indices (due to the additional OLD item)
console.log(OLD[2].revived); // someValue
console.log(NEW[1].revived); // someValue

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

Experience interactive video playback by seamlessly transitioning a webpage video into a pop-up when clicking on an

I want to have a video play as a pop-up when the user clicks a play button, while also fading out the background of the page. It should be similar to the way it works on this website when you click to watch a video. How can I achieve this? <div class=" ...

Incorporating PHP in JS/jQuery AJAX for creating unique odd and even conditional layouts

My PHP code includes a loop that changes the layout of elements based on whether the $count variable is odd or even. For odd counts, an image appears on the left and text on the right. For even counts, it's the other way around. To load content dynam ...

A guide on combining two counters in Vue to create a unified value

Is there a way to track the number of times two buttons are clicked individually as well as together? <div id="app"> <p><button v-on:click="counter1 += 1">Add One More Click</button></p> <p>&l ...

Deserializing JSON properties in a dynamic way

I'm struggling to figure out how to handle deserializing a JSON object with a dynamic property (e.g. UserRequest::567). This dynamic property can have any value, and the UserRequest object contains other JSON properties that I need. I tried creating ...

Need help accessing data from an API using Axios.post and passing an ID?

Can someone help me with passing the ID of each item using Axios.Post in order to display its data on a single page? The image below in my Postman shows how I need to send the ID along with the request. Additionally, I have the first two URL requests for t ...

The error message "node Unable to iterate over property 'forEach' because it is undefined" appeared

I am facing an error and unable to find the solution. I believe my code is correct. It is related to a video lesson where I attempt to display popular photos from Instagram using the Instagram API. However, when I try to execute it, I encounter this issue. ...

An action in redux-toolkit has detected the presence of a non-serializable value

When I download a file, I store it in the payload of the action in the store as a File type. This file will then undergo verification in the saga. const form = new FormData(); if (privateKey && privateKey instanceof Blob) { const blob = new Blo ...

Understanding how to retrieve the FileType from a Document Object Model using JavaScript

Looking at this DOM structure, we have an image with the following details: <img id="this-is-the-image" src="http://192.168.1.100/Image_tmp/2016-06/d4eb8d"> The task at hand is to click a button, execute a JavaScript function, and download the ima ...

Troubleshooting issue: Django and Javascript - Why is my dependent dropdown feature not

I am new to using a combination of Javascript and Django. Below is the script I have written: <script> $(document).ready(function() { $("#source").change(function() { var el = $(this); var reg = ...

creating a while loop in node.js

In C#, the following code would be used: double progress = 0; while (progress < 100) { var result = await PerformAsync(); progress = result.Progress; await Task.Delay(); } This concise piece of code spans just 7 lines. Now, how can we ...

Modifying Div Size with Jquery

I am working on populating the div container with square boxes, but I'm having trouble adjusting the size of my #gridSquare div. Despite trying to change its height and width using jQuery, it doesn't seem to work as expected. $('#gridSquare ...

Issue encountered in AngularJS while configuring resources for the action `query`: Anticipated response was an object, but received an array instead

I've been attempting to utilize Angular 1.3 to access a REST service, but I keep encountering an error stating "Error: error:badcfg Response does not match configured parameter". My suspicion lies in the controller where I invoke $scope.data. Even th ...

Unable to retrieve Angular Service variable from Controller

I am facing an issue with my Angular Service. I have set up two controllers and one service. The first controller fetches data through an AJAX call and stores it in the service. Then, the second controller tries to access this data from the service. While ...

How do the authentication and authorization processes in my frontend connect with the backend of my API system?

Currently, my frontend is built with Vue while my backend relies on an express rest API that fetches data from mysql. My goal is to ensure security for both the frontend (specifically a login form) and backend API without limiting access solely to my front ...

What steps should be taken to incorporate a user input space similar to the one found in the Wordpress new post section

I am looking to incorporate a user input section on my website similar to the one found in WordPress for creating new posts. I would like this area to have all of the same tools available, such as adding hyperlinks, bolding text, and uploading images. Ca ...

I'm sorry, but we were unable to locate the /bin/sh

After running a command using execSync that runs with sh, I observed the following: spawnSync /bin/sh ENOENT bin is now included in the PATH environment variable. Any ideas on this issue? ...

An issue has occurred while trying to execute the npm start command within PhpStorm

When I try to run npm start on Windows' command prompt, it works fine. However, I encounter errors when running it in the PhpStorm Terminal. You can see the errors here. Is this a result of them being different platforms or could it be related to som ...

Is there a way to customize the JSON-wrapped key for a class without being able to annotate the class with @JsonTypeInfo?

I have the following code snippet: import org.codehaus.jackson.map.*; public class MyPojo { int id; public int getId() { return this.id; } public void setId(int id) { this.id = id; } public static void main(String[] args) throws ...

Adjust Fabric js Canvas Size to Fill Entire Screen

Currently, I am working with version 4.3.1 of the Fabric js library and my goal is to adjust the canvas area to fit its parent div #contCanvasLogo. I have tried multiple approaches without success as the canvas continues to resize on its own. Below is the ...

What is the best way to allow all authenticated routes to display the Devise ajax Login form?

I have successfully incorporated Devise to accept Ajax Login and have designed a form for logging in via ajax, displayed within a modal. However, I am only able to view the form and login when I set up event binders for specific buttons that activate the m ...