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

"Learn how to pass around shared state among reducers in React using hooks, all without the need for Redux

I've built a React hooks application in TypeScript that utilizes multiple reducers and the context API. My goal is to maintain a single error state across all reducers which can be managed through the errorReducer. The issue arises when I try to upd ...

Identifying the precise image dimensions required by the browser

When using the picture tag with srcset, I can specify different image sources based on viewport widths. However, what I really need is to define image sources based on the actual width of the space the image occupies after the page has been rendered by th ...

Issue with transferring variables between functions in JSON and Jquery

I'm currently working on a script that involves retrieving the variable hf using getJSON $.getJSON('../scripts/json.php', function(json) { var user_function = json.hf; }); In addition to this, I have developed an auto_refresh feature ...

Is it possible to save jQuery plugin initialization settings for future use?

Is it possible to save a default set of settings for a lightbox jQuery plugin, including options and callback functions, in a variable or array that can be referenced later in different contexts with varying configurations? For example, could I initially ...

Using Selenium: Checking for existing dropdown values and incrementing if necessary

I am currently working on automating an application using Selenium Webdriver with Java. The web application I am testing has an Add button that, when clicked, triggers the activation of a dropdown menu. Subsequent clicks on the Add button reveal additional ...

jQuery code runs smoothly on Firefox but encounters issues on Chrome

I'm experiencing an issue with a script that is supposed to post a comment and load the answer from a server. The script works fine in Firefox, but in Chrome, it seems that no event is triggered. You can click the button, but nothing happens. I'v ...

Changing a zero-prefixed string into JSON format using Swift 4

When attempting to encode an integer that starts with a 0 into JSON using swift 4, I encountered an issue. Even though I am utilizing a standard JSONSerialization library, I am facing difficulties in serializing the data after converting the string to utf ...

Using React Router useHistory to navigate to different routes programmatically

Currently, I'm working on creating a wizard interface and running into some issues with the buttons. Right now, I have next and back buttons for each route, but I am aiming to create a button component that can handle navigation both forward and backw ...

Refreshing a jsp page without the need to reload the content

On my jsp page, I am displaying the contents of a constantly changing table. This means that users have to refresh the page every time they want to see updated information. Is there a way for me to update the content dynamically without requiring users t ...

Adding event listeners to modal buttons in a Handlebars template is a simple process that involves utilizing the `

I've been working on developing a web application that interacts with a news API to display articles. Each article is presented in a card format, and I have also incorporated modals using handlebars. My goal is for each card's button to trigger ...

Tips for resolving the error "React import attempt":

I'm a beginner in learning React and I encountered this error when trying to export NavigationMenu and import it into Navigation: Failed to compile ./src/components/Navigation.js Attempted import error: 'NavigationMenu' is not exported from ...

What is the process for moving entered data from one text box to another text box when a checkbox is selected?

I need help with a function that reflects data entered in one text box to another text box when a checkbox is ticked. The checkbox is initially checked and the values should change when it is unchecked and then checked again. Currently, the code is only ou ...

Utilize Gson to generate and analyze JSON data containing nested objects including a local date

I encountered an error while trying to parse my JSON data. java.lang.IllegalStateException: Expected a string but was NAME at line 1 column 313 path $.reminder com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was ...

Fixing the hydration error in Next 13 can be challenging, especially when it occurs outside of a Suspense boundary

Encountering an issue while working with Next.js 13: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <div> in <html>. Every time I attempt to r ...

When JavaScript evaluates special characters in HTML, it interrupts the function call within an AJAX response

Recently, I have been developing a custom form completion feature for a website/tool that I am working on. After successfully implementing the search functionality, which displays results below the input field, I wanted to enable users to select a result ...

Using the concept of method chaining in JavaScript, you can easily add multiple methods from

Hey there! I'm looking for some assistance with dynamically building a method chain. It seems like it should be pretty straightforward if you're familiar with how to do it... Currently, I am using mongoose and node.js to query a mongo database. ...

Having trouble retrieving JSON with crossDomain jQuery AJAX

The process I followed was creating a rails 3.0 scaffold and exposing it using json, keeping it running. When accessing http://localhost:3001/objects.json I can view json data in the browser Next, I had a simple html file with code.jquery.com/jquery-1.7 ...

Substitute specific characters in a string using Regex or Gsub

Struggling to find the correct answer, I'm considering altering the question. Presented below is a JSON code snippet: [ { "section_id": "58ef93aaa310c97c0c16bcd2", "name": "Name1", "slug": "slug1" }, { "section_id": "58ef93aaa3 ...

How can I update a CSS class value by utilizing AngularJS variables?

I am currently facing an issue with making my CSS values dynamic. The code I have tried is not functioning as expected. <style> .panel-primary { background-color:{{myColorPanel}} } </style> I came across a similar query on Ho ...

"Issues Arising from Compatibility between Internet Explorer, jQuery,

I need help creating a function that will transfer items from the basket to the cart. The code I have written works well in Firefox and Chrome, however, it is not recognizing the products. var modals_pool = {}; $('.deal_order_btn').on('clic ...