Update an array by breaking it into smaller chunks, while maintaining the original index positions

I am faced with a situation where I must update an existing array by utilizing its chunks to perform a specific operation. While I have a functional solution in place, I am concerned about the performance implications and I am eager to determine if my current approach is optimal.

const parentArray = [
    {
    key: 0,
    customerId: 'customer 0',
    partyType: 'party 0',
    date: '2020-05-25T17:17:38.910Z',
  },
  {
    key: 1,
    customerId: 'customer 1',
    partyType: 'party 1',
    date: '2020-05-26T17:17:38.910Z',
  },
  {
    key: 2,
    customerId: 'customer 2',
    partyType: 'party 2',
    date: '2020-05-27T17:17:38.910Z',
  },
  {
    key: 3,
    customerId: 'customer 3',
    partyType: 'party 3',
    date: '2020-05-28T17:17:38.910Z',
  },
];

const childArray = [
    {
    key: 1,
    customerId: 'customer 01',
    partyType: 'party 01',
    date: '2020-05-25T17:17:38.910Z',
  },
  {
    key: 3,
    customerId: 'customer 21',
    partyType: 'party 21',
    date: '2020-05-27T17:17:38.910Z',
  },
];

const mergeArraysHandler = (parentArray, childArray, key) => {
    return parentArray.map((item, i) => {
      const record = childArray.find(record => record[key] === item[key]);
      if (record) {
        return record;
      }
      else {
        return item;
      }
    });
}

console.log(mergeArraysHandler(parentArray, childArray, 'key'));

As illustrated above, I have developed a method that takes the parent array, child array, and a unique property as inputs to execute the necessary checks. As anticipated, this method merges the two arrays while maintaining the original indexing and updating the parent array accordingly.

Answer №1

Incorrect approach - instead of repeatedly searching in child array, it is better to index it by key just once for improved performance. This can be achieved with ease.

const mergeArraysHandler = (parentArray, childArray, key) => {
  const childArrayMap = childArray.reduce((agg, v) => {
    agg[v[key]] = v
    return agg
  }) // or you can use lodash function _.keyBy instead of this

  return parentArray.map(item => childArrayMap[item[key]] || item)
}

Alternatively, you can achieve the same result with a single line using the lodash function keyBy

const mergeArraysHandler = (parentArray, childArray, key) => 
  _.values({
    ..._.keyBy(parentArray, key), 
    ..._.keyBy(childArray, key)
  })

If the arrays are sorted by key, the fastest code would be:

const mergeArraysHandler = (parentArray, childArray, key) => {
    const arrays = [
       { array: parentArray, index: 0, value: parentArray[0] },
       { array: childArray, index: 0, value: childArray[0] },
    ]

    const res = []
    while (arrays.some(v => v.value)) {
       const ind = Number(arrays[1].value && arrays[0].value &&
         arrays[1].value[key] <= arrays[0].value[key])

       res.push(arrays[ind].value)
       const changes = ind && arrays[1].value[key] === arrays[0].value[key] ? [0, 1] : [ind]

       changes.forEach(ind => arrays[ind].value = arrays[ind].array[++arrays[ind].index])
    }

   return res
}

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

Despite using callbacks when passing props in React JS components, the rerendering still occurs

In my React project, I implemented callbacks to prevent excessive rerendering due to the large amount of data being displayed and numerous buttons that trigger these rerenderings when clicked by the user. The useCallback hooks are effective in preventing ...

The link in Next.js is updating the URL but the page is not refreshing

I am facing a peculiar issue where a dynamic link within a component functions correctly in most areas of the site, but fails to work inside a specific React Component - Algolia InstantSearch (which is very similar in functionality to this example componen ...

Notify of an Invalid CSRF Token within the Action Buttons Present in the Table

I've encountered a problem with the CSRF token when using a Handlebars each loop. I created a data table using the each loop but I'm unable to submit the delete button. The CSRF token only seems to work for submitting new data (POST) and updating ...

What is the mechanism behind the operation of the square brackets operator?

Currently focused on C programming, however, this question pertains to low-level concepts that transcend specific languages. I am curious about how a program effectively retrieves the correct data using array[0] or array[6], irrespective of the type of da ...

Unexpected behavior in the AngularJS UI Bootstrap datepicker causing dates to shift

Hi there, I have encountered an issue with setting the default date format (YYYY-MM-DD) in the UI Bootstrap datepicker input field using momentjs. Everything seems to display correctly until I try to console log the selected date. It appears that an additi ...

Having trouble running a form due to the inclusion of JavaScript within PHP code

My PHP code includes a form that connects to a database, but when I add JavaScript to the same file, the form does not execute properly. (I have omitted the insert code here.) echo '<form action="$_SERVER["REQUEST_URI"];" method="POST">'; ...

Transferring information between a service and a controller

I'm struggling to pass data between a service and a controller in my AngularJS project. Even though I've followed the recommended steps, the code is not functioning as expected. Below is the controller snippet: function udpController($scope ...

"Error occurred: Unable to execute bgColor as a function" on HTML select onchange event

I am having an issue with my HTML switch that has an onchange tag triggering the JavaScript function bgColor with the argument this. However, every time I attempt to use this, I receive an error message: Uncaught TypeError: bgColor is not a function. Can a ...

Where should the webapp files for a Node.js application be located within the server directory?

Can someone help clarify a question I have been struggling with? I have created a nodejs webapp with a specific directory structure, as shown in the screenshot. This app will eventually incorporate MongoDB and store a large number of audio files. I am usi ...

Encountered an error with symbol '@' while utilizing ES6 decorators

I have recently set up a React project and now I'm attempting to integrate MobX into it. This requires using decorators such as: @observable However, when I try to implement this, I encounter the following error: https://github.com/mobxjs/mobx Mod ...

"Bootstrap-Wizard: How to troubleshoot the onPrevious function not working when used with an

I have been incorporating a bootstrap wizard into one of my applications, and I have encountered an issue. When attempting to utilize the index position of the tabs to achieve a specific goal, I found that it only works with the next button and not with th ...

Guide on accessing and setting values in GridView Cell using JavaScript

Within my layout, I have two labels named FixedTotal and TotalPercent, as well as a single row GridView with columns labeled ReferenceID, Percentage, and Amount. ReferenceID Percentage Amount -------------- ------------- --- ...

Creating a RESTful API

To begin with, I am a newcomer to web frameworks and we are currently using Meteor. In our database, we have a collection of Students: Students = new Mongo.Collection('students'); At the moment, we have defined a Rest API as follows: // Maps t ...

Generating hyperlink regions dynamically

I am looking to create an image with a link map that will contain multiple areas that need to be updated frequently. Instead of constantly recreating the areas every few seconds, I want to generate them only when the user clicks on the image. I initially ...

Gatsby Dazzling Graphic

I'm currently facing an issue with my Heroes component. const UniqueHero = styled.div` display: flex; flex-direction: column; justify-content: flex-end; background: linear-gradient(to top, #1f1f21 1%, #1f1f21 1%,rgba(25, 26, 27, 0) 100%) , url(${prop ...

Using AJAX in a WordPress template

I'm currently facing an issue with integrating my operational php/javascript/ajax application into my WordPress theme. This application is meant for my users and not within the admin panel. Steps I've taken: I have successfully included the Java ...

Sending values from multiple input fields created in PHP using AJAX can be done by following these steps

https://i.sstatic.net/GKcRc.png Within this snippet, there is a portion of a form that consists of 4 different fields/divs like the one shown. I am struggling to figure out how to send the values of these input fields to PHP using AJAX. I apologize if ...

"Converting circular structure into JSON" - Inserting BigQuery Data using Cloud Function in Node.js

I am currently facing an issue while attempting to load an array of JSON objects into a BigQuery Table from a Cloud Function built in NodeJS. Despite not having any circular references, I encountered the error message "Converting circular structure to JSON ...

Vue.js Ajax call is throwing a bizarre error: TypeError - str.replace function not recognized

Recently, I encountered a puzzling error message: vue-resource.common.js Uncaught TypeError: str.replace is not a function while working on an ajax call to retrieve some data: export default { data: () => ({ recipes: [] }), ready() { ...

Setting the default value of a multi-select dropdown in AngularJS from the controller

Currently, I have implemented AngularJS multi select drop down functionality on my website. The code for this can be found at the following source: MultiSelectDropDown In my HTML page, I have included the same drop down twice and I want to customize the ...