Combine arrays using underscore or lodash

Hello, I need some assistance.

I have a couple of arrays containing grades with associated classes attributes like the examples below:

var arr1 = [{
        "id": 53,
        "name": "Grade 1 AppMonkeyzTest",
        "classes": [{
            "id": 54,
            "name": "Class 1A AppMonkeyzTest"
        }, {
            "id": 55,
            "name": "Class 1B AppMonkeyzTest"
        }, {
            "id": 59,
            "name": "Class BG1 AppMonkeyzTest"
        }]
    }, {
        "id": 54,
        "name": "Grade 2 AppMonkeyzTest",
        "classes": [{
            "id": 56,
            "name": "Class AA1 ppMonkeyzTest"
        }, {
            "id": 57,
            "name": "Class BA1 AppMonkeyzTest"
        }]
    }];  
    

and

var arr2 = [{
        "id": 53,
        "name": "Grade 1 AppMonkeyzTest",
        "classes": [{
            "id": 58,
            "name": "Class BB1 AppMonkeyzTest"
        }]
    }];
    

My goal is to combine them into a single array of grades with unique classes for each grade ID, as shown below:

var merge = [
            {
                "id": 53,
                "name": "Grade 1 AppMonkeyzTest",
                "classes": [{
                    "id": 54,
                    "name": "Class 1A AppMonkeyzTest"
                }, {
                    "id": 55,
                    "name": "Class 1B AppMonkeyzTest"
                }, {
                    "id": 59,
                    "name": "Class BG1 AppMonkeyzTest"
                }, {
                    "id": 58,
                    "name": "Class BB1 AppMonkeyzTest"
                }]
            },
            {
                "id": 54,
                "name": "Grade 2 AppMonkeyzTest",
                "classes": [{
                    "id": 56,
                    "name": "Class AA1 ppMonkeyzTest"
                }, {
                    "id": 57,
                    "name": "Class BA1 AppMonkeyzTest"
                }]
            }];
    

Answer №1

Utilize the _.merge function with a callback, demonstrated below:

var arr1 = [{
    "id": 53,
    "name": "Grade 1 AppMonkeyzTest",
    "classes": [{
        "id": 54,
        "name": "Class 1A AppMonkeyzTest"
    }, {
        "id": 55,
        "name": "Class 1B AppMonkeyzTest"
    }, {
        "id": 59,
        "name": "Class BG1 AppMonkeyzTest"
    }]
}, {
    "id": 54,
    "name": "Grade 2 AppMonkeyzTest",
    "classes": [{
        "id": 56,
        "name": "Class AA1 ppMonkeyzTest"
    }, {
        "id": 57,
        "name": "Class BA1 AppMonkeyzTest"
    }]
}];

var arr2 = [{
    "id": 53,
    "name": "Grade 1 AppMonkeyzTest",
    "classes": [{
        "id": 58,
        "name": "Class BB1 AppMonkeyzTest"
    }]
}];

var res = _.merge(arr1, arr2, function (a, b) {
    if (_.isArray(a)) {
        return a.concat(b);
    }
});

console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.3/lodash.js"></script>

Answer №2

In this JavaScript code snippet, we are merging two arrays of objects based on a shared property.

var arr1 = [{
    "id": 53,
    "name": "Grade 1 AppMonkeyzTest",
    "classes": [{
        "id": 54,
        "name": "Class 1A AppMonkeyzTest"
    }, {
        "id": 55,
        "name": "Class 1B AppMonkeyzTest"
    }, {
        "id": 59,
        "name": "Class BG1 AppMonkeyzTest"
    }]
}, {
    "id": 54,
    "name": "Grade 2 AppMonkeyzTest",
    "classes": [{
        "id": 56,
        "name": "Class AA1 ppMonkeyzTest"
    }, {
        "id": 57,
        "name": "Class BA1 AppMonkeyzTest"
    }]
}];
var arr2 = [{
    "id": 53,
    "name": "Grade 1 AppMonkeyzTest",
    "classes": [{
        "id": 58,
        "name": "Class BB1 AppMonkeyzTest"
    }]
}];
var arr3 = [];
for (var i in arr1) {
    arr3.push(arr1[i]);
    for (var j in arr2) {
        if (arr2[j].id == arr1[i].id) {
            for (var k in arr2[j].classes) {
                arr3[i].classes.push(arr2[j].classes[k]);
            }

        }
    }

}
console.log(arr3);  

Check out the demo here!

Answer №3

To efficiently merge arrays, you can utilize the _.findIndex() method:

var combinedArray = [];

firstArray.forEach(function(item){
    var index = _.findIndex(combinedArray, { id: item.id });
    if(index){
        combinedArray[index].classes = combinedArray[index].classes.concat(item.classes)
    } else {
        combinedArray.push(item);
    }
});

secondArray.forEach(function(item){
    var index = _.findIndex(combinedArray, { id: item.id });
    if(index){
        combinedArray[index].classes = combinedArray[index].classes.concat(item.classes)
    } else {
        combinedArray.push(item);
    }
});

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

The function window.scrollBy seems to be causing a conflict with jjmslideshow, resulting in the page being unable to

I wrote a simple script to create a "smooth scroll" effect when a specific link is clicked: (function() { 'use strict'; // Checking for compatibility if ( 'querySelector' in document && 'addEventListener' in window ...

Unable to access current props within useEffect block

When I use useEffect with the parameter props.quizStep, my function fn (which is a keydown event listener) is unable to access the current value of props.quizStep. I'm puzzled as to why it's not working properly. Can you help me understand? Bel ...

Apply the "ng-class" directive only if there is an <a> element located after the specified element

My issue involves a list of items categorized by labels, with a search filter applied. The problem arises when the labels appear in the search results even though the lists themselves are empty. I need to hide the relevant label if there are no items prese ...

Is it possible to implement the same technique across various child controllers in AngularJS?

I am trying to execute a function in a specific child controller. The function has the same name across all child controllers. My question is how can I call this function from a particular controller? Parent Controller: app.controller("parentctrl",functi ...

TinyMCE: Tips for adding and highlighting text in your content!

Is there a way to insert, or even replace the current selection with some content and then have it automatically selected? Take for instance this text: Hello nice world! The user has selected nice. After clicking a button, this code is executed: editor. ...

I'm having trouble utilizing toastify.js after installing it via npm. I keep receiving the error message "Failed to resolve module specifier." Any advice

Currently, I am attempting to utilize Toastify-js, a library designed for toast type messages, by installing it through npm. In the provided documentation, following the execution of the installation command, there is a direction that states: - To begin ...

Determining the Right Version of a Framework in npm: A Guide

One common issue I encounter is the uncertainty of which versions of npm, Ionic, and other tools I should have installed. It often goes like this: "Oh, there's a new version of the Ionic CLI out. Let's update." I install CLI v3.9.0. ...

What are alternative ways to add an HTML snippet to an existing file without relying on jQuery?

Is it possible to inject the entire content of an HTML file, including all tags, into a specific div using only JavaScript? Alternatively, would it be necessary to append each element individually and create a function for this purpose? ...

What is the best way to turn each function within the module pattern into a promise?

Utilizing Angular 1.5, I have developed a factory function that returns a literal object structured as follows: return { item: null, get: function() { return item; }, create: function() { if (this.get()){ this.remove(); ...

Discover and update values in JSON using JavaScript

Currently, I am working on generating graphs using d3.js with a JSON file as the input. My main challenge lies in parsing the date and time format for the x-axis. Below is the code snippet that I have attempted: d3.json('data/fake_users11.json', ...

Encountered a build issue following the Svelte update: The subpath package './compiler.js' is not recognized by the "exports" definition

Challenge After updating from Svelte version 3.0.0 to the latest using npm i svelte@latest, I encountered an issue where my application would not run and constantly displayed the following error: [!] Error: Package subpath './compiler.js' is n ...

Steer clear of manually inputting URLs in your React components

As I embark on my journey with Gatsby, I am noticing a recurring pattern in my code. A prime example is when creating links, where I often find myself doing something like this: import {kebabCase} from "lodash"; // ... <Link to={`tags/${kebabCase( ...

When using Ajax in Jquery and expecting data of type JSON, the response always seems

Looking to create a basic jQuery Ajax script that checks a user's discount code when the "Check Discount Code" button is clicked? Check out this prototype: <script> jQuery(function($) { $("#btn-check-discount").click(function() { c ...

When attempting to parse a JSON feed with jQuery and innerHTML, the data fails to display

Having trouble parsing a JSON feed using jQuery and innerHTML, but for some reason it's not working as expected. No errors are being displayed in the console and the feed itself is functioning properly. Not quite sure why this issue is occurring. < ...

What is the process of choosing a language (English/French) within a pop-up?

<body style="text-align:center"> <h2>Popup</h2> <div class="popup" onclick="myFunction()">Interact with me to show/hide the popup! <span class="popuptext" id="myPopup">A Simple Popup!</span> </div> <script& ...

The functionality of loading JSON is not working properly in ePub3

Currently, I am working on a project involving the creation of an ePub3 eBook. One of the exciting features I have successfully integrated is three.js to showcase some models. My next goal is to develop 'hotspot' elements (small cubes that users ...

Iterate through the array and show the information using Angular

enter image description hereI am a beginner in Angular and I am looking to iterate through an array in Angular. The array contains the following elements: "ticketsdetectives":[10,11,12,13] My goal is to display this data similar to the following ...

What is the best way to post an image using nodejs and express?

Recently, I've been working on a CMS for a food automation system and one feature I want to incorporate is the ability to upload pictures of different foods: <form method="post" enctype="multipart/form-data" action="/upload"> <td>< ...

Can someone please explain how to use the prevState in REACT?

Can you explain the difference between how to define the counterHandler function in these two examples? counterHandler = () => { this.setState(() => { return { times: this.state.times + 1 } }); } versus counterHandle ...

Difficulty in transmitting two boolean values using ajax and setTimeout()

I am working on two functions that are supposed to send either 0 or 1 to a PHP page using AJAX. When a key is pressed on the keyboard, the function that sends 1 should start, followed by the second function that sends 0 three seconds later using setTimeout ...