How can you merge two arrays with identical property values in Javascript?

Is there a way to combine arrays with the same property value without using map due to different indexes?

var array1 = [
        {'label':"label1",'position':0},
        {'label':"label3",'position':2},
        {'label':"label2",'position':1},
    ];

var array2 = [
        {'label':"label1",'value':"TEXT"},
        {'label':"label2",'value':"SELECT"}
     ];

desired outcome:

var array3 = [
        {'label':"label1",'value':"TEXT",'position':0},
        {'label':"label2",'value':"SELECT", 'position':1}
     ];

Here is my attempt that is not working:

var arr3 = arr1.map(function(v, i) {
        return {
            "label": v.label,
            "position": v.position,
            "value": arr2[?].value
        }
   });

Answer №1

If you're looking to accomplish a task similar to this, you may want to consider utilizing the array#reduce method. Here's an example:

var array1 = [
        {'label':"label1",'position':0},
        {'label':"label3",'position':2},
        {'label':"label2",'position':1},
    ];

var array2 = [
        {'label':"label1",'value':"TEXT"},
        {'label':"label2",'value':"SELECT"}
     ];

var array3 = array2.reduce((arr, e) => {
  arr.push(Object.assign({}, e, array1.find(a => a.label == e.label)))
  return arr;
}, [])


console.log(array3);

Answer №2

To find a new object, one option is to utilize a Map and verify its presence.

var array1 = [{ label: "label1", position: 0 }, { label: "label3", position: 2 }, { label: "label2", position: 1 }],
    array2 = [{ label: "label1", value: "TEXT" }, { label: "label2", value: "SELECT" }],
    map = array1.reduce((m, o) => m.set(o.label, o), new Map),
    array3 = array2.reduce((r, o) => {
        if (map.has(o.label)) {
            r.push(Object.assign({}, o, map.get(o.label)));
        }
        return r;
    }, []);

console.log(array3);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

When it comes to determining which array(s) will have labels that are subsets of the other (if any), there is a method that accommodates the possibility of either `array1` or `array2` having labels that are not present in the other array. This method involves using `reduce` on `array1` and using `find` to locate the matching label in `array2` if it exists:

var array1 = [
  {'label':"label1",'position':0},
  {'label':"label3",'position':2},
  {'label':"label2",'position':1},
];
var array2 = [
  {'label':"label1",'value':"TEXT"},
  {'label':"label2",'value':"SELECT"}
];

const output = array1.reduce((a, { label, position }) => {
  const foundValueObj = array2.find(({ label: findLabel }) => findLabel === label);
  if (!foundValueObj) return a;
  const { value } = foundValueObj;
  a.push({ label, value, position });
  return a;
}, []);
console.log(output);

Answer №4

In our analysis, we make the assumption that array1 contains all the labels found in array2.

Firstly, we create a map for array2 with the keys being the labels. Then, we filter out items in array1 that have labels existing in the map. Finally, we merge the objects of the filtered array with their corresponding values from the map extracted from array2.

var array1 = [{'label':"label1",'position':0},{'label':"label3",'position':2},{'label':"label2",'position':1}];
var array2 = [{'label':"label1",'value':"TEXT"},{'label':"label2",'value':"SELECT"}];
     
let map = array2.reduce((a,{label, ...rest}) => Object.assign(a,{[label]:rest}),{});
let result = array1.filter(({label}) => map[label]).map(o => ({...o, ...map[o.label]});
console.log(result);

We can further optimize performance by replacing the filter and map functions with Array.reduce in the code snippet above.

var array1 = [{'label':"label1",'position':0},{'label':"label3",'position':2},{'label':"label2",'position':1}];
var array2 = [{'label':"label1",'value':"TEXT"},{'label':"label2",'value':"SELECT"}];
     
let map = array2.reduce((a,{label, ...rest}) => Object.assign(a,{[label]:rest}),{});
let result = array1.reduce((a,o) => {
if(map[o.label]) a.push({...o, ...map[o.label]});
return a;
}, []);
console.log(result);

Answer №5

Check out Array.prototype.map() and Map for further details.

// Input.
const A = [{'label':"label1",'position':0},{'label':"label3",'position':2},{'label':"label2",'position':1}]
const B = [{'label':"label1",'value':"TEXT"},{'label':"label2",'value':"SELECT"}]

// Combine Union.
const mergeUnion = (A, B) => {
  const mapA = new Map(A.map(x => [x.label, x]))
  return B.map(y => ({...mapA.get(y.label), ...y}))
}

// Result + Verification.
const output = mergeUnion(A, B)
console.log(output)

Answer №6

Success!

Method: Merge the entities with identical description, utilizing the Object.assign() function

var set1 = [{'description':"desc1",'position':0},{'description':"desc3",'position':2},{'description':"desc2",'position':1}];
var set2 = [{'description':"desc1",'value':"TEXT"},{'description':"desc2",'value':"SELECT"}];
var output = [];

set2.forEach(function(entity, idx){
    output.push(Object.assign({}, set1.find(function(e, i){ return e.description == entity.description }), entity));
});

console.log(output)

Answer №7

My knowledge of javascript is limited, but there is another way to achieve the same result.

    var array1 = [
    {'label':"label1",'position':0},
    {'label':"label3",'position':2},
    {'label':"label2",'position':1},
];

    var array2 = [
    {'label':"label1",'value':"TEXT"},
    {'label':"label2",'value':"SELECT"}
 ];
     var array3=[];
 for(var i=0;i<array1.length;i++)
    {
        for(var x=0;x<array2.length;x++)
        {       
                console.log(array1[i]['label'] == array2[x]['label']);
                if(array1[i]['label'] == array2[x]['label']){
                array3.push({label:array1[i]['label'],value:array2[x]['value'],position:array1[i]['position']});

                }
        }        
    }
    console.log(array3);

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

Using a Button component as a TableCell in a material-ui Table

Hey there! I'm looking for some assistance in adding buttons as TableRowColumns in the material-ui Table. I'm working on implementing an approval system to approve or reject user requests, and I thought presenting them in a tabular format would b ...

Is there a way to extract information from the HTML source code of an external website and display it in my application?

Seeking a method to search an external URL for content that matches "title" and then display the results on my HTML page using Javascript. Despite my efforts with Javascript, I have not come across any resources that address this issue. Could it be that I ...

I am looking to create a password generator that saves all generated options to a file

I am looking to create a custom password generator that writes all generated options to a file. For example, using the numbers "0123456789" and having a password length of 3 characters. However, I am facing an issue with the file writing process where it ...

When using Sequelize, I encountered an error message from SQLite stating that the table does not exist despite having created

I am struggling to grasp the concept of how Sequelize operates and I can't figure out why I am encountering the SQLITE_ERROR: no such table: Users error even though I have created the table using sequelize.define. Here is my code: const { Sequelize, D ...

Leveraging ng-class for designing a favorite symbol

How can I implement ng-class to toggle an icon when it is clicked, taking into account whether it is stored in local storage? For example, changing the favorite icon from outline to solid upon user click. Below is my current implementation using ng-class ...

Transferring SQL server dates to jQuery Calendar through AJAX communication

I am currently working on implementing a jQuery calendar example, and I want to load the dates from my SQL database instead of using hardcoded values. I am considering using Ajax post to send a request to my web method and retrieve the data. However, I am ...

The reason for my inability to include a fresh method in String.prototype using typescript

I attempted to extend the String.prototype with a new method, but I encountered an issue. interface String { newMethod(): void } String.prototype.newMethod = function() {} Although there were no errors in the typescriptlang.org playground, I received ...

Angular ng-repeat with toggle filter

Looking for a way to display data in an angular application using ng-repeat? Want to add and remove filters on the displayed data with a simple click? You're in luck. Implementing a toggle filter functionality is easier than you think. If you've ...

Creating interactive popups using Web Map Service (WMS) with the

I am looking for a way to make a leaflet map loaded from a geoserver interactive by displaying popups with information. Can someone provide a solution using jsfiddle to help me understand? I am struggling to figure out how to achieve this. Essentially, I w ...

What is the process for building .ts components within a Vue application?

Looking to update an old project that currently uses the 'av-ts' plugin and vue-ts-loader to compile .ts files as Vue components. The project is running on Vue 2.4.2, but I want to upgrade it to version 2.6.14. However, since 'vue-ts-loader& ...

How important is a neglected parameter in the world of JavaScript?

Curious about the value of an ignored parameter in JS? Imagine a function that requires 2 values as parameters, but you only provide one during the call. What happens to the other parameter? You might think it's undefined, but the code below only show ...

What is the best way to eliminate data from a channel title using jQuery?

$(function() { $(".track").draggable({ containment:"document", appendTo:document.body, connectToSortable:"#playlist tbody", revert: true, revertDuration: 0, cursor: "move", helper: "clone", ...

Ways to match a string against a numeric value

I have a span id with textContent which have their own time(hour/minutes) <div class="here"> <span class="time" >8 min</span> </div> <div class="here"> <span class="time" >22 min&l ...

Adding existing tags to Select2 in Angular2 can be accomplished by following these steps:

HTML: <select data-placeholder="Skill List" style="width:100%;" class="chzn-select form-control" multiple="multiple"> <option *ngFor="#skill of allSkills" [ngValue]="skill">{{skill}} </option> </select> TS: allSkills = [& ...

Unable to display the value of my array in JSON encoded PHP due to it being undefined

In my cart.php file, I have encoded an array to JSON and returned it to an AJAX function: $data = array(); $data['total'] = '10000'; $data['quantity'] = '10'; echo json_encode($data); In my index.php f ...

Refresh jQuery DataTable with updated search results

I have a function that loads the DataTable once the document is loaded. $(document).ready(function() { var $dataTable = $('#example1').DataTable({ "ajax": 'api/qnams_all.php', "dataType": "json", "bDestroy": true, "s ...

Is it possible to generate various resolutions of an image simultaneously?

While trying to download wallpapers from a link on this website, I encountered an issue. Upon clicking the download button, a new page opened with the URL "https://images.wallpapersden.com/image/download/street-fighter-fortnite_bGtoaW6UmZqaraWkpJRmbmdlrW ...

Display HTML code within a data attribute

I have a function that modifies an element from OpenLayers. In the official documentation, it mentions that the property label accepts either HTML or a string. methods: { onUpdatePosition (coordinate) { this.deviceCoordinate = coordinat ...

Selecting options from a pop-up menu

I've created a dropdown menu with what seems to be correct code. However, there are no errors showing up, but the selected item from the menu is not alerting as expected. Here is the jsfiddle link $(document).ready(function () { // This function ...

Designing unique variations using Material UI

I am currently exploring the creation of custom variants for the Button component in Material UI. To start off, I am developing a customized component based on the Button component with specific styles: // CTA.js import { makeStyles } from "@materia ...