Tips for retrieving the corresponding second array of objects in ES6

I am working with two arrays of objects and need to find a better solution.

array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];

The expected output should be: When the id from the first array matches the id from the second array, we want to use the name from the second array. In this case, since id 2 matches, the desired result is id:2,name: panasonics.

Output:

 [{id:1,name:"samsung"},{id:2,name:"panasonics"},{id:3,name:"Lg"},{id:5,name:"samsung"},{id:7,name:"Apple"}]

Answer №1

Merge the arrays by using Array.concat(), transform them into a Map based on the id field, and then convert the values of the Map into an array using Array.from():

const mergeArraysByField = (field, ...arrays) => Array.from(
  [].concat(...arrays)
  .reduce((result, object) => result.set(object.id, object), new Map)
  .values()
);

const firstArray = [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
const secondArray = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];

const mergedResult = mergeArraysByField('id', firstArray, secondArray);

console.log(mergedResult);

Answer №2

If you're looking to compare arrays and extract matching elements based on a specific condition, one way to do it is by utilizing the .forEach() loop as demonstrated below (alternatively, you could use a traditional for loop, but the .forEach() method offers simplicity).

The following code snippet iterates through items in array1 and within that iteration, it scans through each item in array2. It then verifies if the IDs match between the two arrays; if they do, the corresponding name is added to the result array.

const array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
const array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];
let result = [];

array1.forEach(e1 => {
  array2.forEach(e2 => {
    if (e1.id == e2.id) {
      result.push(e2.name);
    }
  });
});

console.log(result);

Answer №3

To achieve the desired result, you can utilize the map() and concat() functions in the code snippet below:

let array1 = [{id: 1, name: "Samsung"}, {id: 2, name: "Nokia"}, {id: 3, name: "LG"}];
let array2 = [{id: 5, name: "Samsung"}, {id: 2, name: "Panasonics"}, {id: 7, name: "LG"}];
let newArray = array1.map(function(item, index){
    if(array2[index].id === item.id){
        return array2[index];
    } else {
        return item;
    }
});
let finalArray = newArray.concat(array2);
console.log(finalArray);

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

Switch between light and dark modes with the MUI theme toggle in the header (AppBar)

I'm currently working on implementing a feature that allows users to switch between dark and light themes in my web app. The challenge I am facing is how to ensure that this theme change functionality is available throughout the entire app, not just i ...

Problem: Vue 3 build does not generate service worker

After adding the "@vue/cli-plugin-pwa": "^4.5.12" to my package.json and setting up workbox configuration in my vue.config.js, I encountered an issue. When running npm run build:prd with the script vue-cli-service build --mode prod.exam ...

Encountering a TypeScript error when using Redux dispatch action, specifically stating `Property does not exist on type`

In my code, there is a redux-thunk action implemented as follows: import { Action } from "redux"; import { ThunkAction as ReduxThunkAction } from "redux-thunk"; import { IState } from "./store"; type TThunkAction = ReduxThunk ...

Response Looping Function

I am struggling with looping and storing data in an array. /** Model for displaying response*/ export class ResultsData { id: number, name: string, startDate: string, endDarte: string, startTime: string, ...

Utilize jQuery to deactivate all click interactions except for the scrollbar

I am currently working on creating a page that is completely unclickable, both with right and left clicks, and I want to display a message when someone attempts to click. This may lead to some questions such as "Why would anyone want to do this? This s ...

The .val() and focus() methods are not functioning correctly

I am having an issue with a simple script: when I input a link to an image in the form's INPUT field, it should automatically display a preview of the image: https://example.com/image.jpg However, when I input the same link not by using ctrl+C/ctr ...

Is it possible to utilize Angular.js as a full substitute for a traditional JavaScript template engine?

While angular excels in two-way data binding and single-page applications, could it also serve as a viable replacement for a JavaScript template engine? Let's dive into the potential pros and cons of this approach. ...

When a new element is added to the DOM, bind a click event to it that will trigger another

When I add an element to the DOM, I bind it with a click function. The problem is that if I add multiple elements and click on any of them, the function triggers multiple times. What causes this behavior and is there a better way to achieve the desired res ...

Pull data from another domain's DIV using jQuery's load/ajax function

I need to load content from a different domain into a DIV on my JSP page. For example: $("#myDiv").load("https://www.google.com") The issue I'm facing is that the request is being blocked by the browser's same origin policy. I've explore ...

Leveraging express functions in Node.js framework

Currently, I am delving into the world of nodeJS and have stumbled upon a great collection of tutorials. The tutorials are focused on teaching me about a powerful framework known as express. In order to utilize express effectively, one must also grasp the ...

What causes the discrepancy in values displayed by enums in TypeScript when assigned integers in reverse order?

Recently diving into the world of TypeScript, I've been experimenting with different types in this language. One interesting data type I played with is enums. Here's an example of code I used: enum colors {red=1,green=0,blue,white}; console.lo ...

Generate an automatic "proxy" for ASP.NET MVC Controller to communicate with AngularJs service

Whenever I utilize an ASP.NET MVC controller with AngularJS, the majority of my controller functions consist of JSON results. When creating my AngularJS service, I find myself repeatedly writing similar code to handle GET or POST calls to my ASP.NET contro ...

What could be causing the npm mysql module to malfunction when trying to initiate the 'connect()' function in a separate .js file?

When I call require('mysql') and use the function connect() everything works fine. However, if I try to call the 'connect()' function in another file, it throws an error saying connection.connect is not a function... Any suggestions on ...

Interactive canvas artwork featuring particles

Just came across this interesting demo at . Any ideas on how to draw PNG images on a canvas along with other objects? I know it's not a pressing issue, but I'm curious to learn more. ...

What is the best way to implement React.memo or useMemo and ensure semantic guarantees?

According to the documentation provided for useMemo: While useMemo can improve performance, it should not be solely relied upon for semantic guarantees. React may choose to recalculate previously memoized values in the future, such as to free up memo ...

Limiting input to specific characters is effective on Chrome, but unfortunately does not function on Firefox

This code snippet is designed to restrict user input to lowercase letters from a-z, numbers from 0-9, and the dash character "-". While it functions correctly in Chrome, it does not allow any input in Firefox. What could be causing this issue? $('#sl ...

Bringing in a Native JavaScript File to Your Vue Component in Vue Js

After developing a frontend application using Vue Js, I encountered the need to integrate a native JavaScript file into one of my Vue components. This native js file contains various utility functions that I would like to access and use within my Vue comp ...

In Vue JS, ensure that each item is loaded only after the previous item has finished loading

Is there a way to optimize the loading of around 1000 static images, .gifs, and videos for an online slideshow presentation? Currently, all items are loading simultaneously causing viewers to wait to see the first item. How can each item be loaded after th ...

Bringing an AMD module into a Mocha test

I recently encountered an error while using Mocha to test code that was exported as an AMD module. When running the Mocha test, I received the following error message: ReferenceError: define is not defined at Object.<anonymous> (/home/malintha/proje ...

Generating a unique serial ID using Angular/JS

I am in the process of developing a function that will create a unique serial id by replacing a string with the format; xxxx-xxxx-xxxx-xxxx. The desired outcome is a serial like this: ABCD-1234-EFGH-5678, where the first and third parts consist of letters ...