Transform an Array by replacing a specific value or creating a new one

Dealing with two arrays, both potentially of large lengths:

The goal is to update the status in Array 1 with the corresponding status from Array 2. Here's a sample output:

[{
value: 123,
status: 'demo',
type: '...'
},
{value: 2335,
 status: 'demo2',
 type: 'xxx'
}]

The key challenge here lies in efficiently replacing the status values between the two arrays given their potential size. The order and length may vary, hence requiring strategic linking based on IDs.

Original Data

[
   {
    "id": "55",
    "status": "2",
    "type": "COD",
     "value": "5038.2",
   },
 {
   "id": "56",
   "status": "2",
   "type": "COD",
    "value": "5398.2",
  },
   {
    "id": "57",
    "status": "2",
    "type": "COD",
    "value": "10798.2",
  }

 ]

Array 2

[
   {
     "id": "1",
    "status": "Awaiting Confirmation",
   },
   {
    "id": "2",
    "status": "Confirmed",
   },
   {
    "id": "3",
     "status": "Awaiting Shipment",
  },
  {
     "id": "4",
    "status": "Awaiting Pickup",
   },
   {
    "id": "5",
    "status": "Shipped",
   },
 {
   "id": "6",
    "status": "Delivered",
   },
   {
     "id": "7",
    "status": "Cancelled",
  },
  {
   "id": "8",
    "status": "Refund Requested",
   },
   {
     "id": "9",
     "status": "Refunded",
   }

Attempted Solutions: Utilized lodash library along with a for loop

const output = [];
      for (let i = 0; i < array1.length; i++) {
        const statuscode = array1[i].status;
        const result = _.find(array2, { id: statuscode });
        output.push({
          value: array1[i].value,
          status: result.status,
          type: array1[i].type
        });
      }
      console.log(output);

Answer №1

To optimize performance, consider converting one of the arrays into a Map first. Map lookups are highly efficient:

const data = [{
    id: 1,
    name: 'Alice',
  },
  {
    id: 2,
    name: 'Bob',
  }
];
const map = new Map(Object.values(data).map(({ id, name }) => [id, name]));
console.log(map.get(1)); // Output: Alice

In terms of code readability, it's important to prioritize that over speed. However, if you prefer performance and want to use a for loop instead of .map, here's an example:

const items = [{
    num: 1,
    value: 'first'
  },
  {
    num: 2,
    value: 'second'
  }
];
const itemMap = new Map(items.map(({ num, value }) => [num, value]));

const result = [];
for (let i = 0; i < items.length; i++) {
  const { num, value } = items[i];
  result.push({ num: num, value: itemMap.get(num) });
}
console.log(result);

Answer №2

An easy way to accomplish this task is with a standard `for` loop:

for (let i = 0; i < array1.length; i++) {
  array1[i].status = array2[i].status;
}

This method assumes that both arrays are the same length and in the same order.

UPDATE

If you need to handle different lengths or orders, consider using Array.prototype.find:

for (let i = 0; i < array1.length; i++) {
  const temp = array1[i];
  temp.status = array2.find(x => x.id === temp.status).status;
}

Remember, it's important to prioritize readability over premature optimization for better code maintenance.

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

Guide to updating textarea background color depending on a specific selection

Looking for some assistance with a form I'm working on. It includes fields for Name, Surname, a dropdown menu for selecting different colors, and a message box (textarea). I would like to dynamically change the background color of the textarea based o ...

Flipping the Logical AND Condition

Currently, I am analyzing the following code snippet: // $data is a one-dimensional array and has at least one value starting with a "@" if ( (count($data) == count($data, COUNT_RECURSIVE)) && (count(preg_grep('~^@~', $data)) > 0) ) ...

Error message: The call stack size limit has been exceeded only on Windows when running `npm start` in a server

While working on the serverless stack guide, I encountered a roadblock early on in Windows 10 (without any issues in Mac or Linux). I set up a basic serverless stack project and ran: npm run start And received this error: RangeError: Maximum call stack ...

Encountering issues with gulp-angular-templatecache while processing angular templates through pipelining

I've encountered an issue with gulp-angular-templatecache in my gulpfile. Here's the task causing trouble: gulp.task('templates', function() { return gulp.src(paths.angularTemplates) .pipe(templateCache()) ...

Start the Angular $scope when the page first loads

When initializing a user session with specific data, I face the challenge of making sure that the session data is populated before it is required by certain directives in my application. Currently, I check if the local session data is empty on loading the ...

Error: Unable to register both views with identical name RNDateTimePicker due to Invariant Violation

Encountering an issue while attempting to import: import DropDownPicker from 'react-native-dropdown-picker'; import DateTimePicker from '@react-native-community/datetimepicker'; <DropDownPicker zIndex={5000} ...

The Ajax post is only activated on one occasion

Hello there, I am encountering a problem with an ajax function. My goal is to post data to a database and then update a table that displays the database information. Strangely, the process works fine the first time - data is posted and the table is refresh ...

I constantly receive null values when executing my database query function

I created a query function for my project, but the result always comes back as null. How can I troubleshoot this code? const queryDB = async (collection, filter) => { let result = null await MongoClient.connect(url, function(err, getDb) { if ...

Stop the bootstrap accordion from expanding when a button in its header is clicked

Currently, I am facing an issue with two action buttons located in the header of an accordion. Here is the setup: https://i.sstatic.net/HU2Kp.png Whenever I click on one of these buttons, it toggles the accordion's state. I have attempted to use e.p ...

Issue with executing Jquery in PUG file: The $ sign is not being recognized despite jQuery being imported

I am encountering an issue where my jQuery code placed inside a pug template is not executing as expected. Despite including the jQuery file, when trying to run a jQuery function, I receive the error below: 40| P 41| ...

Tips for displaying an error message when entering an incorrect password using Firebase Simple Login email-password authentication

I am utilizing Firebase's Simple Login as an administrator login for a blog-style website. The correct combination of email and password grants write access to the database on Firebase. Following the provided documentation, I have created distinct sec ...

Issue with ngModel being undefined after data has finished loading in Ionic 3

As a newcomer to Angular 4, I've been struggling to find a solution for a seemingly simple issue related to an Ionic app. Whenever a user logs in, the entire user object is saved to localStorage. Despite trying various plugins, I settled on a straight ...

Request not being sent to the server by the code

I'm encountering an issue with sending a request from my app via the phonegap build solution and a push notifications plugin. Below is the code snippet: function tokenHandler(result) { var channelid; if (subParam == 2) { ...

The field 'name' remains unchanged

I am in the process of developing a VS CODE THEME MAKER that generates a customized JSON file based on user input for colors. Below is all the necessary code: import download from 'downloadjs'; import React, { useState } from 'react'; i ...

Converting an rrule date value from an array to a customized string format

Here is an array that I am working with: [{ evening_feeding: false evening_feeding_time: "19:00" feeding_frequency_rule: **"FREQ=DAILY;INTERVAL=2"** id: 890 morning_feeding: true morning_feeding_time: "04:00 ...

Is there a way to modify the orientation of the bootstrap modal when it opens?

I am trying to modify the way my bootstrap reveal modal opens. I have followed the code instructions provided in this resource, but unfortunately my modal is not opening. I am using angularjs. Can someone assist me with troubleshooting the code? Here is m ...

Converting an array of URI elements into a string for routing within the PHP MVC framework: What's the best approach?

Encountered Challenges I've been facing some minor hurdles with the routing in an MVC framework that I'm developing. Although the code seems correct at first glance, there seems to be an issue with how I've handled the breakdown of the requ ...

Generating dynamic anchor tags in Vue.JS

I have a JavaScript object that I want to convert into HTML elements and display it in Vue.js. So far, my approach has been to convert the object into strings representing HTML elements and then add them to the template. However, even though this method di ...

The jQuery click event is failing to trigger

I am facing an issue with some buttons that have specific classes. Here is an example: https://i.sstatic.net/CVIR2.png Each of these buttons contains JSON data stored in a data attribute. I have created a function to detect when a button is clicked and p ...

What is the method for retrieving the fixed information?

I am currently working on a project that involves creating a course-rating API. We have been given a completed angular application to work with, and our task is to set up the routes without making any changes to the Angular app. One of the initial tasks a ...