Exploring the Power of Math Set Functions with Associative Arrays in Javascript

Is there a way to find the variance between two sets of objects in Javascript? For example:

var obj1[0] = { name : 'test1' , type : 'test2' };
var obj1[1] = { name : 'test2' , type : 'test3' };
var obj2[0] = { name : 'test1' , type : 'test2' };
var obj2[1] = { name : 'test3' , type : 'test4' };

I am looking to output something like this:

If Intersection() :
obj3[0] = { name : 'test1' , type : 'test2' }
If difference obj1-obj2 :
obj4[0] = { name : 'test2' , type : 'test3' };
If difference obj2-obj1 :
obj5[0] = { name : 'test3' , type : 'test4' };

My search has not yielded any results related to associative arrays.

Answer №1

function checkEquality(x, y){
       return (x.name === y.name && x.type === y.type);            
    }

    function checkPresence(array, object){
        var length = array.length;

        for(var i = 0; i < array.length; i++){
            if(checkEquality(array[i], object)) return true;                               
        }

        return false;        
    }    

    function duplicateObject(obj){
        return {
            name: obj.name,
            type: obj.type
        };        
    }


    function findIntersection(x, y){
        var commonElements = [];    
        if(!x.length || !y.length) return commonElements;

        var lengthX = x.length;
        for(var i = 0; i < lengthX; i++){
            if(checkPresence(y, x[i])){
                commonElements.push(duplicateObject(x[i]));   
            }            
        }

        return commonElements;              
    }




    function findDifference(x, y){
       var resultArray = [];    
        if(!x.length || !y.length) return resultArray;

        var commonElements = findIntersection(x, y);
        var lengthX = x.length;

        for(var i = 0; i < lengthX; i++){
            if(!checkPresence(commonElements, x[i])){
                resultArray.push(duplicateObject(x[i]));   
            }               
        }

        return resultArray;
    }

    var array1 = [{ name : 'test1' , type : 'test2' },{ name : 'test2' , type : 'test3' }];

    var array2 = [{ name : 'test1' , type : 'test2' }, { name : 'test3' , type : 'test4' }];

    console.log(findIntersection(array1, array2));
    console.log(findDifference(array1, array2));
    console.log(findDifference(array2, 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

Eliminate the jQuery AJAX timestamp from the URL parameters

Is there a way to eliminate the jQuery AJAX cache buster code (_=3452345235) from string URLs? While working on a global AJAX fail handler, I need to identify which URL failed. However, every time I locate the failed request's URL, the jQuery cache q ...

Change the ng-model of the initial controller when a button is clicked in a separate controller

I am working on an AngularJS application that has two controllers. I am facing an issue where I need to update the ng-model of an input field in the first controller by clicking a button in the second controller. Accessing the $scope of the first controlle ...

Exclude weekends from DateTime

Currently working on a task list and aiming to set the default date to 3 days from now, excluding weekends. Utilizing Vue and thinking a computed property might be the solution? DateTime.utc().plus({ days: 3 }).toFormat('yyyy-MM-dd HH:mm:ss'), ...

Unable to display toast notification in React/MUI/Typescript project

Currently tackling error notifications targeted at 400,401, and 500 errors within a large-scale project. I am facing an issue where I want to integrate my ErrorToastNotification component into my layout.tsx file to avoid duplicating it across multiple page ...

Utilizing dynamically assigned ng directives in my unique custom directive

I'm in the process of creating a customized table element that looks like this: <datatable items='tableItems' columns='columnsConfig' /> Here, 'tableItems' represents my array of items and 'columnsConfig&apos ...

c# simulating button click through injected JavaScript

Greetings, I'm seeking assistance in replicating a specific button click on a website. Here is the code for the button: <button type="button" class="btn btn-link btn-xs" onclick="getComponents('188855', '5a0f44a9d70380.12406536&apo ...

Guide to combining two vectors with a scalar, storing the outcome in one vector, and returning that vector from a function in the C programming language

I'm facing a little challenge here that I need some help with: I've been studying for an exam and one of my tasks is to create a program that can perform the following operations on two given vectors x and y, which are elements of R^(n). Ea ...

Confirming user credentials for every page

I am currently working with an HTML page that includes front end PHP for server side scripting. One issue I have encountered is the configuration page, which can be accessed by disabling JavaScript in Mozilla settings. My current validation method relies ...

Vue.js v-cloak lifecycle method

Currently, I am working on a project where I have styled v-cloak with display: none, and it is decorating the body. As a result, everything remains hidden until the Vue instance is ready. I have created a component that inserts a chart (using highcharts). ...

Refresh the HTML webpage using AJAX technology

I am trying to implement a simple html page with a single table that updates in the background every 5 seconds. The traditional solution of using <meta http-equiv="refresh" content="5"> is not suitable as it would disrupt the user experience by displ ...

Having trouble accessing a React component class from a different component class

I just started learning reactjs and javascript. For a simple project, I'm working on creating a login and registration form. The issue I'm facing is that when a user enters their email and password and clicks 'register', instead of movi ...

Invoke a function from a page that has been reloaded using Ajax

After making an Ajax request to reload a page, I need to trigger a JavaScript function on the main page based on certain database conditions. This is necessary because I require some variables from the main page for the function. PHP code: if($reset_regi ...

Show pagination control only when there are multiple pages in AngularJS using ui-bootstrap

Currently, I am working with ui-bootstrap pagination and facing an issue where the pagination controls are still visible even when all the results are displayed on a single page. A quick glance at the image below confirms this problem. It seems like a basi ...

Every single data attribute is unique for each element

Hello! I'm currently working on creating a sorting system for pictures, documents, and videos. Each div contains data-extension attributes, so my plan is to filter out all attributes that are jpg, gif, or png and make them visible while hiding the oth ...

We could not locate the requested resource with a DELETE request using the fetch JSON method

Currently, I am in the process of developing a webpage that utilizes JSON API REST alongside XAMPP with an Apache server. Up until now, everything has been working smoothly as I have been utilizing the DELETE method successfully. However, I seem to have hi ...

The header that sticks on scroll is annoyingly blocking the content

I managed to create a sticky on-scroll header/navigation bar successfully. Here is how it looks now However, I encountered an issue. When it reaches the top, it automatically 'covers' the top part of my content, which has text on it, and I don& ...

Customizing a tinyMCE button with a unique icon

I'm attempting to insert a Font-Awsome icon into a button that I included in tinyMCE using the following code: ed.addButton('youtube', { title: 'Add Video' , icon: 'icon-youtube', onclick: function () { ...

Is it possible to develop a web-based chat application using socket.io without the need for ssh access or having to keep the terminal

I have been using php to develop my website. Up until now, I have relied on setTimeout with ajax for updating chats simultaneously. However, when this method stopped working, I discovered socket.io. My goal is to implement private messaging, and while I ha ...

Get a Google Sheets file in CSV format

Currently, I am in the process of developing cloud functions for pushing data to Google AutoML. I have successfully created a function to generate the necessary data. However, for the next phase, I am curious about the possibility of downloading a Google ...

How can I make my navbar stay fixed in place and also activate the transform scale functionality?

After fixing the position of my navbar with the class "top," I noticed that the transform property scale does not work on the div element I applied. The hover effect on the box only works when I remove the position from the navbar. This is the HTML code: ...