Steps for eliminating duplicates in an array while considering additional keys

Consider the following arrays:

const a1=[
  {
    a:{ name: "first" }
  },
  {
    b:{ name: "second" }
  },
  {
    c:{ name: "third" }
  },
  {
    d:{ name: "fourth" }
  }
]

const a2=[
  {
    a:{ name: "first", shelf: "read" }
  },
  {
    b:{ name: "second", shelf: "current" }
  }

]

The task at hand is to compare the content of a1 with that of a2, and if any matches are found, update those items in a1 by adding the missing 'shelf' property.

The expected result should be:

[
  {
    a:{ name: "first", shelf: "read" }
  },
  {
    b:{ name: "second", shelf: "current" }
  }
  {
    c:{ name: "third" }
  },
  {
    d:{ name: "fourth" }
  }
]

An attempted solution involved using map for both arrays and checking for matching names, but due to not having access to the inner map's return value, the original array was returned. A proposed alternative could be concatenating the arrays and utilizing JavaScript's reduce method to check and update the shelf property accordingly. Any suggestions on a more effective approach would be greatly appreciated.

Answer №1

In order to optimize the looping process, I would start by creating an Auxiliary object for "a2". While iterating through each element in array a1, I would then check if the current key exists in the auxiliary object.

Utilizing an Auxiliary Object helps avoid unnecessary iterations, as you only need to traverse both arrays once.

const a1 = [{x: {title: "first"}}, {y: {title: "second"}}, {z: {title: "third"}}, {w: {title: "fourth"}}];

const a2 = [{x: {title: "first", category: "fiction"}}, {y: {title: "second",category: "non-fiction"}}];

const dictionary = a2.reduce((accumulator, obj) => { 
  const [key, value] = Object.entries(obj)[0];
  accumulator[key] = value;
  return accumulator;
}, {});

const updatedA1 = a1.map((obj) => {
  const [key, value] = Object.entries(obj)[0];
  if (dictionary[key]) {
    Object.assign(value, dictionary[key]);
  }
  return {[key]: value};
});

console.log(updatedA1)

Answer №2

This code snippet offers a concise solution to the problem at hand:

array1.map((item) => {
    const key = Object.keys(item)[0];
    const array2Item = array2.find((item2) => Object.keys(item2)[0] === key);
    if (array2Item) {
        Object.assign(item[key], array2Item[key]);
    }
    return item;
});

Keep in mind that this operation modifies the elements of the original array1.

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

We encountered an issue while trying to bootstrap react with the './node_modules/bootstrap/dist/js/bootstrap.min.js' module. The error was a result of the module not being able

Error : I encountered a problem when trying to add a navbar using Bootstrap. Without importing the jQuery part, the navbar works but the collapsing feature does not work. However, when I add the jQuery part, I receive the following error: ./node_modules ...

Submitting forms from a different router in React can pose a unique challenge

As a beginner in React, I am working on creating a simple meal app. In my App component, I am fetching meal data from an api and allowing users to click on a meal for more details. However, I am facing an issue where searching for a new meal on the detail ...

Rotate images with animation using Javascript

Seeking assistance with a swinging motion using two simple functions in Javascript. As a newcomer to the language, I am looking for guidance to achieve my goal. First function: function up() { imgObj.style.left = parseInt(imgObj.style.transform = 'r ...

The webpage is displaying an error stating that "<function> is not defined."

I recently duplicated a functional web page into a new file on my site. However, after adding a new function and removing some HTML code, the JavaScript function no longer runs when clicking one of the two buttons. Instead, I receive the error message "Beg ...

In search of an explanation for why Promise outcomes for an inline function are not resolving to the desired return value

I have been exploring JavaScript promises and encountered an issue while trying to consolidate promise logic from separate functions into a single inline function. Combining everything into one inline function is causing the return result of the promise to ...

Discovering the correct index of the optgroup element within selected options

When the "obj" object receives the "optgroup" elements as parameters and their corresponding options as values, an issue arises when options from both optgroups are selected. In this case, all option values are returned from the first optgroup and the prev ...

Swap out a particular component during the testing phase

Currently, I am running tests on my React-Redux application using Jest. Within my API calls, I have integrated a fetch module called cross-fetch. However, I am looking to substitute this with fetch-mock. Take a look at my directory structure: Action.js i ...

Transitioning to utilizing Bootstrap through npm

I am currently working on a project that utilizes Bootstrap. However, the Bootstrap files are being loaded into a subdirectory. I would like to transition to using npm for easier maintenance and updates. Within our existing style folder, we have subfolder ...

Discovering the most efficient method for locating elements within a 2D cell array

Consider the following 2D cell array structure: my_cells= Columns 1 through 11 {1x6 cell} {1x8 cell} {1x2 cell} {1x7 cell} {1x7 cell} {1x6 cell} {1x7 cell} {1x7 cell} {1x8 cell} {1x5 cell} {1x7 cell} Columns 12 through 22 ...

What is the best way to retrieve ejs data within a form when implementing express?

When a user requests, the following HTML file is displayed in the code below. I also need to access the values of clubname and type inside the app.post() function in my app.js file. <!DOCTYPE html> <html> <head> <title><%= t ...

Deleting text after an answer has been given using jQuery or JavaScript

I seem to have encountered a problem with the logic I've implemented. The desired functionality is for the user to enter an answer to the question presented. Upon submitting the answer, the current text (first question) should disappear and the next q ...

extracting information from an external document

I'm quite new to both three.js and JavaScript, so please bear with me if this is a simple question. I have a JSON file with a list of objects containing data like this: [ { "x":x,"y":y,"z":z ,"r":r}, { "x":x2,"y":y2,"z":z2 ,"r":r2}, { "x":x3,"y":y3, ...

Is there a way to filter out only the data for the month of August from a particular

$arr = [ (Object)[ 'interval' => "2018-08-26", 'product_id' => 12 , 'size' => 10 ], (Object)[ 'interval' => "2018-09-26", 'pr ...

What You See Is What You Get editor options

CKEditor is a fantastic HTML editor, but I've encountered an issue when pasting HTML structure and switching to WYSIWYG mode. The editor automatically reformats the HTML structure, causing unexpected changes to the original layout. I'm intereste ...

Utilize jQuery to serialize the HTML input elements that are dynamically generated outside of the form

A proof of concept is in progress for an application that involves the generation of HTML elements based on user-configured fields. Here is a sample configuration: // Customer SAM $response = array( array ( NAME => CUSTOMER, TYPE = ...

Instructions on extracting a random element from an array and continue removing elements from the array until it is completely empty

I am attempting to utilize either jquery or javascript to remove a random item from an array until it is empty. Each time I remove an item, I want to log it to the console. My goal is to create elements with random images from the specified array until all ...

Utilizing Jquery for transmitting and receiving data

As a newcomer to application development, I have been struggling with figuring out how to send and retrieve data using the latest version of JQuery. My main concern is ensuring that the functionality I implement is compatible with all browsers. While I ha ...

Is there a way to implement infinite scrolling in my MUI DataGrid component?

Hey there! I have a custom component that needs to have infinite scrolling added to it. I tried looking into MUI DataGrid for solutions, but didn't have much luck implementing anything successfully. Currently, I'm fetching data using GraphQL and ...

Struggling to maintain the value of my variable outside of the getJSON function

Hello, I'm currently facing an issue with this code. The problem lies in the fact that the first console.log(smile_per_sec) outputs the correct value I require, but the second one displays the value I initially assigned to it when declaring the variab ...

The values returned by the Node.js API can vary for identical requests

I am currently learning how to use Node.js + Express in order to create a REST API. Within this API, I have implemented the following method: apiRouter.route('/training/session/byId/:id_session') // ===== GET ======= .get(function(req, res ...