Discover the object in the initial array that is not included in the second array using AngularJS

Imagine having these two sets of objects:

first set:

[
    {
        id: "123",
        title: "123",
        options: []
    },
    {
        id: "456",
        title: "456",
        options: [
            {
                id: "0123",
                title: "0123",
                options: []
            }
        ]
    },
    {
        id: "789",
        title: "789",
        options: []
    },
]

and the second set:

[
    {
        id: "123",
        title: "123",
        options: []
    },
    {
        id: "789",
        title: "789",
        options: []
    },
]

In the second array, a part is missing:

{ id: "456", title: "456", options: [ { id: "0123", title: "0123", options: [] } ] }

What would be the correct and efficient method to iterate through and identify missing elements in Angular?

Answer №1

If you want to achieve this, consider the following approach:

<div ng-app>
    <div ng-controller="MyCtrl">{{availableGroups}}
    </div>
</div>

JavaScript code snippet:

function MyCtrl ($scope) {
    $scope.groups = [
    {
        id: "123",
        title: "123",
        options: []
    },
    {
        id: "456",
        title: "456",
        options: [
            {
                id: "0123",
                title: "0123",
                options: []
            }
        ]
    },
    {
        id: "789",
        title: "789",
        options: []
    },
];

    $scope.assignedGroups = [
    {
        id: "123",
        title: "123",
        options: []
    },
    {
        id: "789",
        title: "789",
        options: []
    },
];


    $scope.availableGroups = (function () {
        var assignedGroupsIds = {};
        var groupsIds = {};
        var result = [];

        $scope.assignedGroups.forEach(function (el, i) {
          assignedGroupsIds[el.id] = $scope.assignedGroups[i];
        });

        $scope.groups.forEach(function (el, i) {
          groupsIds[el.id] = $scope.groups[i];
        });

        for (var i in groupsIds) {
            if (!assignedGroupsIds.hasOwnProperty(i)) {
                result.push(groupsIds[i]);
            }
        }

        return result;    
    }());
}

To see a working example, click on this jsFiddle link.

Thank you.

Answer №2

If we have two arrays, let's call the first one 'first' and the second one 'second'. We can start by sorting both of them:

function sortFunction(a, b){
    if(a.id < b.id) return -1;
    if(a.id > b.id) return 1;
    return 0;
}

first.sort(sortFunction);
second.sort(sortFunction);

Next, we can go through each array to identify any missing elements:

var missingElements = {};
for(var i = 0, j = 0; i < first.length; ++i){
    if(first[i].id == second[j].id){
        j++;
        continue;
    }
    missingElements.push(first[i]);
}

The 'missingElements' array will now contain objects that are present in the first array but not in the second.

It's important to note that this code does not rely on AngularJS; it is written in plain Javascript.

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

Exploring the intricacies of mapping an Array of Arrays

I'm currently tackling a data manipulation project that involves iterating through an array of arrays and generating a single string containing all possible combinations found within these arrays. For instance: const array = [ [{id: 1}, {id: 2}], ...

Implementing auto-population of input field in Vue JS based on dropdown selection

I'm in search of a solution for automatically filling input fields in Vue.js. My form consists of various input types such as text, select dropdowns, and quantities. I want the vCPU, vRAM, and Storage Capacity fields to be filled with predefined value ...

Position a component in relation to another component using AngularJS

Utilizing ng-show and ng-hide, I created a descriptive box that appears below text when clicked. However, there is an issue as the description box does not align directly under the text, similar to what is shown in this image https://i.stack.imgur.com/phBh ...

Create a function signature that can take in any 2D integer array as a parameter, no matter how the user decides to input it

To provide a practical example: #include <stdlib.h> #include<stdio.h> void demonstrate_function(int size , int array[][size]); int main(void){ int x; /*Static 2D Array*/ int data[2][2]; /*Various Techniques for Dynamically Allocating 2D Ar ...

Ways to establish a connection with a directive attribute

I am trying to customize the title for the highchart using $scope.data.title, but currently, the attribute interprets data.title as a string and binds it to the scope. I attempted to use "", {{}} around data.title in the .html file, but it did not work. It ...

What is the most effective method for comparing two arrays of objects and extracting the differing values within a React application?

I am currently working on implementing a changelog feature for my website. Let's consider the initial array as initArray: [ { "id": 1, "val1": "2023-08-28", "val2": 1, " ...

``When you click, the image vanishes into thin

Could you please explain why the image disappears once I close the lightbox? Access with password: chough ...

When invoking a service repeatedly in Angular within a loop, the result is returned on the second iteration rather than the first

I've run into an issue where I'm attempting to invoke a service in Angular within a for loop and store the result in a Map. map = new Map<string, string[]>(); this.effectivitiesList = this.trimEffectivities.split(","); for (let ...

What are the best practices for integrating QML with Java?

How can QML be interfaced with Java when developing the GUI and API for a linux based device? ...

Exploring the syntax of typescript when using createContext

Just starting out with typescript and I have some questions. Could someone break down the syntax used in this code snippet for me? What is the significance of having two groups containing signIn, signOut, and user here? Is the first group responsible fo ...

Is there a way to use JavaScript to switch the entire div on and off

I have a function called done that I want to use to toggle the visibility of my "temp" division. tasks.innerHTML += `<div id="temp"> <span id="taskname"> ${input.value} </span> <button class="d ...

Switch between two AppBars simultaneously while scrolling in Material UI

In my Header.js component, I have two AppBars. The first one is sticky and the second one is not initially visible. As we scroll down, I want the second AppBar to collapse and the first one to stay stickied at the top of the screen. I looked at the Materi ...

After clicking the create button in AngularJS, the ngModel values become empty

My form has been simplified by using ngRepeat to create the input fields. The attributes for each item are defined in my controller. Below is the code for the ModalCtrl: ... $scope.form = [ { label: 'First Name', fieldType: 't ...

Discovering when the DOM has finished rendering in AngularJS with ng-repeat

I am looking for a way to trigger an alert or message upon completion of rendering in my HTML DOM using AngularJS, specifically when dealing with multiple ng-repeats. HTML Code: <body> <div ng-controller="Ctrl"> <div ng-repeat= ...

How can you limit access to certain routes in Nuxt.js to only clients who possess a valid JWT token?

In Nuxt.js, implementing authentication can be done in the following steps: The client authenticates by sending its credentials in an HTTP request to a specific API route in the Nuxt backend; The Nuxt backend responds with a JWT token for accessing protec ...

Displaying information collected from a submission form

I am in the process of designing a cheerful birthday card and I need to transfer data from a form to the birthday card page. How can I take information from the first div (which contains the form) and display that data in the second div? <!DOCTYPE ...

Add() function is not duplicating the formatting

I'm attempting to replicate the content below inside a DIV. <ul class="pie-legend"><li><span style="background-color:#0066CC"></span>10-0-1</li><li><span style="background-color:#33CC33&q ...

Switching back and forth between classes prevents the animation from playing continuously, causing it to jump straight to the end

Currently, I am in the process of animating a hamburger menu with a unique twist. The idea is to have the top and bottom lines smoothly translate to the middle and then elegantly rotate into an X shape when clicked. My approach involves toggling between tw ...

The window.addEventListener function is failing to work properly on mobile devices

Hey there! I am facing an issue in my JS code. I wrote this code because I want the menu to close when a visitor clicks on another div (not the menu) if it is open. The code seems to be working fine in developer tools on Chrome or Firefox, but it's no ...

Chunk error ECONNREFUSED trigger

Encountered an issue while running through grunt. Getting a proxy error: Econnrefused when trying to run grunt serve. After running --verbose, it seems like the request is being blocked. I suspect it may be due to my organization's network setup, bu ...