Adding elements to a multi-dimensional array that match elements from another array

I am working with two arrays:

a = [
  [a, b],
  [c, d],
  [e, f],
  [g, h]
]

b = [
  [a, 4],
  [1, 2],
  [e, 3]
]

My challenge lies in updating the elements of array a when they match corresponding elements in array b. Specifically, I need to add a new value to the matched element of a. For example, if a[0][1] matches b[0][1], then a[0][1] should be updated to [a,b,new_value].

If creating a new array with all values of a is necessary, that's acceptable. However, it's crucial that the original values and order of a remain unchanged.

Despite my attempts at utilizing various types of loops, I'm struggling to achieve the desired outcome. Any guidance or solutions provided would be greatly appreciated.

Thank you sincerely.

Answer №1

Using a map function along with the find method seems to work fairly well when dealing with arrays a and b. The goal is to iterate through each item in array a and check if there is a corresponding element in array b, then add a new value:

const a = [
  ["apple", "banana"],
  ["cat", "dog"],
  ["elephant", "fox"],
  ["goat", "horse"],
];

const b = [
  ["apple", 4],
  [1, 2],
  ["elephant", 3],
];

const mappedArray = a.map(item => {
  const matchingElement = b.find(element => element[0] === item[0]);
  if (matchingElement) return [...item, "new data"] // Update "new data" as needed
  return item;
});

console.log(mappedArray)

Answer №2

Loop through the first array using Array#map. Check if the first element of each sub-array matches the corresponding sub-array in the second array. If there is a match, append a value to the sub-array from the first array using concat and return it. Otherwise, return the sub-array as is.

Note: Using concat and map will create new arrays without modifying the original ones.

var arr1 = [["apple","banana"],["cat","dog"],["elephant","fox"],["giraffe","horse"]];

var arr2 = [["apple",4],[1,2],["elephant",3]];
     
var updatedArr = arr1.map(function(subArr, index) {
  return arr2[index] && subArr[0] === arr2[index][0] ? subArr.concat(arr2[index][1]) : subArr; // Replace arr2[index][1] with any desired value
});

console.log(updatedArr);

Answer №3

To handle arrays of different lengths, one approach is to use a default value when mapping the result of the comparison.

var array1 = [['x', 'y'], ['m', 'n'], ['o', 'p'], ['q', 'r']],
    array2 = [['x', 4], [5, 6], ['o', 3]],
    result = array1.map((arr, index) => arr.concat(arr[0] === (array2[index] || [])[0] ? array2[index][1] : []));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Transform objects into arrays

Is there a way to transform an object into an array of objects while adding new keys and values? This is my current object: { "0": "Ann_B", "1": "Billy_P", "2": "Carly_C", "3": "David_L" } I would like it to look like this: [ { "value": "Ann_B ...

Implementing conditional rendering using custom division return functions with onClick attribute on a submit button in React: A step-by-step guide

import React from "react"; class Input extends React.Component { constructor() { super(); this.state = { phone: "", weight: "", height: "", gender: "", smoke: "", lazy: "", bmi: "", pain: "", ...

What could be the reason for jQuery not functioning properly as needed?

function toggleDisplayingRooms(nameSelect){ if(nameSelect){ firstroom = document.getElementById("firstroom").value; secondroom = document.getElementById("secondroom").value; thirdroom = ...

Troubleshooting: Issues with jQuery Dropdown Menu

I'm currently working on a website that includes a settings feature with a button. My goal is to have the options and other links display in a dropdown menu when hovered over. Although I have written what I believe to be the correct code, it's no ...

Troubleshooting issue with Onchange in select HTML element within Django

I'm working with a Problems model in my project. In my Models file models.py class Problems(models.Model): Easy = 'Easy' Medium = 'Medium' Hard = 'Hard' NA = 'NA' DIFFICULTY = [ (NA ...

Unbounded AngularJS 1.x looping of Ag-grid's server-side row model for retrieving infinite rows

I am obtaining a set of rows from the server, along with the lastRowIndex (which is currently at -1, indicating that there are more records available than what is being displayed). The column definition has been created and I can see the column headers in ...

Why is my array.sort statement in ReactJS not functioning properly?

This question has been puzzling me for ages, despite the fact that it has probably been answered countless times. I have an array called products that contains various product objects, each with properties like name, price, amount, store name, and image UR ...

Retrieve the values of the recently selected options in a multiple selection

I am trying to retrieve the last or most recently selected option value from a dropdown menu. In my Django code, I have attempted the following: <script type="text/javascript> django.jQuery(document).ready(function(){ django ...

Messy code appeared when sending an AJAX post to JBoss EAP 7 without using encodeURIComponent

Initially, the project functions smoothly on tomcat using UTF-8 and jboss eap 6 with UTF-8 page encoding as well. Additionally, the jboss configuration includes: <servlet-container name="default" default-buffer-cache="default" stack-trace-on-error="loc ...

"Embracing AngularJs with the power of SocketIo

Can someone please help me with the code snippet provided below? This code is sourced from: http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets app.factory('socket', function ($rootScope) { var socket = io.connect(); return { ...

What is the best way to alter the header in Django when a user is authenticated?

In my project, I have two headers: header.html and headersuccess.html. When a user is logged in, I need to change the header from header.html to headersuccess.html. How can I implement that? Here is an excerpt from my views.py file where I render loginsuc ...

Animate CSS Grid to dynamically fill the viewport on top of current grid elements

Please note that I am specifically seeking vanilla JS solutions, as jQuery is not compatible with this project I have a grid structure that is somewhat complex: body { margin: 0; height: 100vh; text-align: center; } .grid-container { ...

What is the best way to arrange an array of words expressing numerical values?

Is there a way to alphabetize numbers written as words (one, two, three) in Javascript using Angularjs? I need to organize my array of numeric words $scope.Numbers = ["three", "one", "five", "two", ...... "hundred", "four"]; The desired output should be ...

What is the best way to iterate over each character in a string and trigger a function in JavaScript?

I am currently working on a project to create a random password generator. The code responsible for generating the password is functioning correctly. However, I am facing an issue with converting the characters of the password into phonetic equivalents. I ...

Obtaining a complete element from an array that includes a distinct value

I'm attempting to retrieve a specific item from an array that matches a given value. Imagine we have an array const items = ["boat.gif", "goat.png", "moat.jpg"]; We also have a variable const imageName = "boat" Since we don't know the file ex ...

Developing a Javascript object using Typescript

Trying my hand at crafting a TypeScript object from JavaScript. The specific JavaScript object I'm attempting to construct can be found here: https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.2/chess.js In the provided JavaScript example, the obj ...

What's the most effective method for looping through a substantial array in order to save data into SQLite using Node.js?

Let's consider a scenario where I am inserting data into a table using a for loop like the example below: ... for(let i=0;i<data.length; i++){ db.run(`INSERT INTO db (a, t, p, q, bM) VALUES (?, ?, ?, ?, ?)`, [data[i].a, data[i].t, data[i].p, da ...

What is the process for displaying HTML page code received from an AJAX response?

My current project involves implementing JavaScript authentication, and I have a specific requirement where I need to open an HTML file once the user successfully logs in. The process involves sending an AJAX request with the user's username and passw ...

I am facing difficulties with deploying my Next.js App on Vercel. Whenever I try to deploy, I encounter an error stating that the Command "npm run build" exited with 1

Hey there! I'm currently following a tutorial by JavaScript Mastery on Next.js (big shoutout to you, sir). I've been trying to deploy it on Vercel, but running into some deployment issues and having trouble testing out different tutorials. Here&a ...

Error: Invalid parameter detected for Shopify script-tag

I'm encountering a persistent error message stating { errors: { script_tag: 'Required parameter missing or invalid' } } This issue arises when attempting to upload a script tag to a storefront. Currently, I'm just experimenting with s ...