Combining two arrays by comparing key values in JavaScript

I am dealing with two distinct arrays. The first one looks like this:

const arrOne = [
    [{sender: '0000', to: '1111'}],
    [{sender: '2222', to: '1111'}]
];

And the second array is structured as follows:

const arrTwo = [
  {
    firstName: 'John',
    lastName: 'Doe',
    num: '1111'
  }
]

My goal is to match the key to from arrOne with the num from arrTwo. If a match is found, I want to update the first array with the corresponding firstname and lastname. Therefore, the desired output should look like this:

  const arrOne = [
        [{sender: '0000', to: '1111', firstName: 'John', lastName: 'Doe'}],
        [{sender: '2222', to: '1111', firstName: 'John', lastName: 'Doe'}]
    ];

This is what I have attempted so far:

arrOne = arrOne.map(item => {
  const item2 = arrTwo.find(i2 => i2.num == item.to);
  return item2 ? { ...item, ...item2 } : item;
});

Thank you in advance for your help. Could you also provide guidance on achieving this using TypeScript?

Answer №1

To properly handle your arrOne which is an array of arrays, it's important to consider its structure. It's also necessary to ensure that you exclude the num from elements in arrTwo based on the expected output provided.

let arrOne = [
    [{sender: '0000', to: '1111'}],
    [{sender: '2222', to: '1111'}]
];

const arrTwo = [
  {
    firstName: 'John',
    lastName: 'Doe',
    num: '1111'
  }
];

arrOne = arrOne.map(item => {
  const item2 = arrTwo.find(i2 => i2.num == item[0].to);
  return item2 ? [{ ...item[0], firstName: item2.firstName, lastName: item2.lastName }] : item;
});

console.log(arrOne);

Answer №2

You are on the verge of success, just make a small adjustment by changing item to item[0] (since data in arrOne is nested array) and remember to add [] to enclose the returned result.

let arrOne = [
    [{sender: '0000', to: '1111'}],
    [{sender: '2222', to: '1111'}]
]; // this is a nested array
const arrTwo = [
  {
    firstName: 'John',
    LastName: 'Doe',
    num: '1111'
  }
]

arrOne = arrOne.map(item => {
  const item2 = arrTwo.find(i2 => i2.num == item[0].to)
  return item2 ? [{ ...item[0], ...item2 }] : [item[0]]; // ensure it's returned as an array
});

console.log(arrOne)

Answer №3

Give this code a shot,

 const arrOne = [
    [{ sender: "0000", to: "1111" }],
    [{ sender: "2222", to: "1111" }],
  ];
  const arrTwo = [
    {
      firstName: "John",
      LastName: "Doe",
      num: "1111",
    },
  ];
  const newarrtt = () => {
    let val;
    const newarry = arrOne.map(item => {
      val = arrTwo.find(x => {
        return x.num, item[0].to;
      });

      if (val) {
        return [
          {
            ...item[0],
            firstName: val.firstName,
            LastName: val.LastName,
          },
        ];
      }

      val = null;
    });
    console.log(newarry);
  };
  newarrtt();

The key point here is that your map function isn't returning an object but an array. Therefore, you need to access it as item[0].

Answer №4

This method effectively removes the undesired 'num' property:

const arrOne = [[{sender: '0000', to: '1111'}],[{sender: '2222', to: '1111'}]];
const arrTwo = [{firstName: 'John', LastName: 'Doe',num: '1111'}];
console.log(arrOne.map(i=>[{...i[0], ...Object.fromEntries(Object.entries(
  arrTwo.find(j=>j.num===i[0].to)??{}).filter(([k,v])=>k!=='num')
    .map(([k,v])=>[k==='LastName'?'lastName':k, v]))}]));

To change the name of the 'LastName' property to 'lastName', you can also use this approach:

const arrOne = [[{sender: '0000', to: '1111'}],[{sender: '2222', to: '1111'}]];
const arrTwo = [{firstName: 'John', LastName: 'Doe',num: '1111'}];
console.log(arrOne.map((i,o)=>[{...i[0], ...(o=(arrTwo.find(j=>j.num===i[0].to)),
    (!o?{}:{firstName: o.firstName, lastName: o.LastName}))}]));

Both methods are robust in scenarios where a matching num is not found.

Answer №5

An iteration using forEach method

const dataArr = [
   [{name: 'Alice', age: 30}],
   [{name: 'Bob', age: 25}]
];

const infoArr = [
   {
      name: 'Alice',
      profession: 'Teacher'
   }
];

dataArr.forEach(data => {
   const item = infoArr.find(info => info.name === data[0].name);
   if(item) data[0] = { ...data[0], ...item };
});

console.log(dataArr);

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

I recently installed Syncfusion but am having trouble running the demo code. If anyone has experience with this and can help me troubleshoot, please reach out. I keep encountering an error message

I recently downloaded the syncfusion package, but I am having trouble running the demo code. Can anyone provide guidance on how to execute the demo code? The following error message is displayed: npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email&# ...

A guide to implementing X-Frame-Options in an express.js web application using node.js

My dilemma involves serving static assets within iframes across various desktop and mobile web clients. Specifically, I am seeking guidance on how to whitelist a select group of origins for allowing the setting of X-Frame-Options headers. This will enable ...

How to retrieve a value from an array using a specific name rather than a numerical key

After creating an object and adding an asset b345 with some properties in it, such as: asset = []; asset.push({'b345' : { 'prop1':'value 1', 'prop2': null}}); I aim to dynamically add more assets later into the sa ...

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

Struggling to successfully toggle the visibility of items

I am currently facing an issue with displaying different sets of data based on button clicks. The first block of information is showing correctly upon page load, but when I try to display other blocks by clicking on the corresponding buttons, the info cont ...

Exporting data from JSON to a CSV file

I am attempting to find a solution for converting JSON objects into CSV files. I tried using a 'for...in' loop within another 'for' loop, but encountered an issue where the object properties and length are different. JSON data: [ {"n ...

Show and hide menu items without automatically scrolling the user back to the top of the page

I am currently working on a project where I have an image button that toggles between expanding and collapsing a menu using JavaScript. The issue I am facing is that every time the button is clicked, it takes the user back to the top of the page. My goal ...

Retrieving information from BlobStorage using Service.ts and triggering the NgOnit function

Within the service.ts module, I am fetching data from Azure Blobstorage and attempting to read its contents. service.ts import { Injectable } from '@angular/core'; import { environment } from '../../environments/environment'; import { ...

What is the best way to ensure PyScript is completely initialized, including the environment?

Hey there! I'm hoping to catch a specific message being logged in my browser's console by a script I added to my HTML file, and then trigger a JavaScript action based on that. For instance, when "ABCD:READY" appears in the console, I want to cal ...

Loop through a collection of elements of a certain kind and selectively transfer only certain items to a different collection of a different kind

When working with typescript, I am faced with the challenge of dealing with two arrays: interface IFirst{ name: string; age: number } interface ISecond { nickName: string; lastName: string; } myFirstArray: IFirst[]; mySecondArray: ISe ...

Use Regular Expressions to escape a quotation mark inside a pattern

Looking for a way to replace double quotes within specific characters in a String. Here's an example string: "XML": "<MyTag>"Value1"</MyTag><MyTag2>Value2</MyTag2>" The desired output is: "XML": "<MyTag>\"Value1&b ...

Creating a Checkbox-enabled Muiv5 TreeView for an array of objects: Step-by-step guide

Currently, I am utilizing the muiv5 treeview component to construct a treeview dropdown. Unfortunately, the component does not have built-in checkbox support for selection/deselection. However, after conducting some research, I managed to find a somewhat s ...

Error: The fetch request was unsuccessful [NextJS API]

I keep encountering an error - TypeError: fetch failed after waiting for 300 seconds while requesting an optimization server that requires a response time longer than 300 seconds. The request is being sent from the provided API in NextJS. Is there a way ...

Building an accordion collapse feature in HTML using CSS and JavaScript

I've been working on creating an accordion interface, but I'm facing an issue where only the first collapsible button works properly. The rest of the buttons are not functioning and don't even appear on the page. When I remove the CSS styli ...

React import syntax using dot notation

I've noticed a trend in many react frameworks recommending dot notation for imports. For example, instead of: import Y from 'X/Y'; <Y /> they suggest using: import X from 'X'; <X.Y /> Both methods seem to work ...

The source property in the Nextjs Image tag is not valid

<Image src={"http://localhost:3000/images/img.jpeg"} layout="fill" objectFit="cover" width={"100%"} height={"100%"} /> An error message has appeared: https://i.sstatic.net/jI9mh.png Any s ...

Unable to Retrieve JSON data from server and storing it in a Javascript Array

I'm relatively new to delving into the realm of JavaScript and JSON, and finding it quite challenging. My current struggle involves accessing and parsing a JSON file stored on my web server into a JavaScript object. What I aim to accomplish is parsing ...

I have been struggling to make react-hook-form validate my input correctly ever since I moved the input to its own component

I have a Form.js component that generates a form element. Inside this form element, there is a FormGroup component that accepts props like inputType, inputName, inputPlaceholder, and renders an input field with a label. I am using react-hook-form for input ...

Updating tokens in NodeJS can be achieved by utilizing the router.use function

I am in the process of validating a token and then saving the response as a cookie to be utilized by router.get methods. However, I have encountered an issue where the data is not updating probably because the request object is outdated and not referencing ...

What strategies can I implement to enhance the efficiency of my search suggestions?

I recently implemented a search suggestion feature on my website similar to Google Suggest, but I've noticed that the speed is a bit sluggish... Here's how I set it up: When a user starts typing in the search bar, I use Ajax to send the keyword t ...