The process of comparing two arrays of objects in es6 and filtering out the unmatched arrays

In my Angular application, I'm attempting to retrieve only the updated array that was modified from the user interface.

Within this scenario, I have two arrays in which one of the role names has been changed. My goal is to compare and extract the modified object, returning only those arrays that have been modified (specifically, where the role_name values were altered).

I've made an attempt at filtering using ES6 methods, but it doesn't seem to be functioning correctly.

Could someone assist me in identifying where I may be making a mistake?

var arr1 = [ {
  "num" : null,
  "role_name" : "ABC",
  "profile" : "ff",
  "user" : "1234",
  "rn" : "1",
  "user_name" : "Rywan"
},
{
  "num" : null,
  "role_name" : "DEF",
  "profile" : "ff",
  "user" : "1234",
  "rn" : "2",
  "user_name" : "adecg"
},
{
  "num" : null,
  "role_name" : "GHJ",
  "profile" : "ff",
  "user" : "1234",
  "rn" : "3",
  "user_name" : "dde"
},
{
  "num" : null,
  "role_name" : "RRT",
  "profile" : "ff",
  "user" : "1234",
  "rn" : "4",
  "user_name" : "kumar"
},
{
  "num" : null,
  "role_name" : "SFR",
  "profile" : "ff",
  "user" : "1234",
  "rn" : "5",
  "user_name" : "SASI"
}
];

var arr2 = [ {
  "num" : null,
  "role_name" : "ABC",
  "profile" : "ff",
  "user" : "1234",
  "rn" : "1",
  "user_name" : "Rywan"
},
{
  "num" : null,
  "role_name" : "ROLE_CHANGED",
  "profile" : "ff",
  "user" : "1234",
  "rn" : "2",
  "user_name" : "adecg"
},
{
  "num" : null,
  "role_name" : "GHJ",
  "profile" : "ff",
  "user" : "1234",
  "rn" : "3",
  "user_name" : "dde"
},
{
  "num" : null,
  "role_name" : "RRT",
  "profile" : "ff",
  "user" : "1234",
  "rn" : "4",
  "user_name" : "kumar"
},
{
  "num" : null,
  "role_name" : "SFR",
  "profile" : "ff",
  "user" : "1234",
  "rn" : "5",
  "user_name" : "SASI"
}
];

   let filteredData;
     filteredData = arr1.filter(function(o1){
      //filter out (!) items in arr2
       return arr2.some(function(o2){
           return o1.role_name !== o2.role_name;  
      });
   });
   
   console.log(filteredData);

The desired output should be:

[
{
      "num" : null,
      "role_name" : "ROLE_CHANGED",
      "profile" : "ff",
      "user" : "1234",
      "rn" : "2",
      "user_name" : "adecg"
    }
]

Answer №1

It seems your reasoning is a bit flawed as the .some() method will always return true since there will be at least one element that is different. The actual check you need to perform is to see if any of the role names match. When no matches are found (i.e., .some() returns false), then you can conclude that the role_name has been altered:

const filteredData = arr2.filter((o1, i) => {
  return !arr1.some((o2) => {
    return o1.role_name === o2.role_name;
  });
});

var arr1 = [{
    "num": null,
    "role_name": "ABC",
    "profile": "ff",
    "user": "1234",
    "rn": "1",
    "user_name": "Rywan"
  },
  {
    "num": null,
    "role_name": "DEF",
    "profile": "ff",
    "user": "1234",
    "rn": "2",
    "user_name": "adecg"
  },
  {
    "num": null,
    "role_name": "GHJ",
    "profile": "ff",
    "user": "1234",
    "rn": "3",
    "user_name": "dde"
  },
  {
    "num": null,
    "role_name": "RRT",
    "profile": "ff",
    "user": "1234",
    "rn": "4",
    "user_name": "kumar"
  },
  {
    "num": null,
    "role_name": "SFR",
    "profile": "ff",
    "user": "1234",
    "rn": "5",
    "user_name": "SASI"
  }
];

var arr2 = [{
    "num": null,
    "role_name": "ABC",
    "profile": "ff",
    "user": "1234",
    "rn": "1",
    "user_name": "Rywan"
  },
  {
    "num": null,
    "role_name": "ROLE_CHANGED",
    "profile": "ff",
    "user": "1234",
    "rn": "2",
    "user_name": "adecg"
  },
  {
    "num": null,
    "role_name": "GHJ",
    "profile": "ff",
    "user": "1234",
    "rn": "3",
    "user_name": "dde"
  },
  {
    "num": null,
    "role_name": "RRT",
    "profile": "ff",
    "user": "1234",
    "rn": "4",
    "user_name": "kumar"
  },
  {
    "num": null,
    "role_name": "SFR",
    "profile": "ff",
    "user": "1234",
    "rn": "5",
    "user_name": "SASI"
  }
];

const filteredData = arr2.filter((o1, i) => {
  return !arr1.some((o2) => {
    return o1.role_name === o2.role_name;
  });
});

console.log(filteredData);

Answer №2

This solution offers a slightly different approach compared to what we have seen before.

By utilizing Object.keys() along with filter(), we can compare the properties of role_name based on array indexes to identify changes such as

arr1[index].role_name !== arr2[index].role_name
. This method will pinpoint all indexes where values have changed. Subsequently, using map(), we can create a new array for those elements according to the identified keys in the array.

Therefore, the proposed solution is:

Object.keys(arr1).filter(index => arr1[index].role_name !== arr2[index].role_name)
                 .map(index => arr2[index]);

Object.keys():

The Object.keys() method returns an array of property names from a given object that are enumerable, following the same order as a regular loop iteration would provide.

Array.prototype.filter():

The filter() method generates a new array containing elements that successfully pass the provided function's test conditions.

Array.prototype.map():

Using map(), a new array is formed with outcomes derived from applying the specified function to every element within the calling array.

I suggest giving this implementation a try:

const arr1 = [{...},{...},...];
const arr2 = [{...},{...},...];

const changedObjects = Object.keys(arr1).filter(index => arr1[index].role_name !== arr2[index].role_name)
                                        .map(index => arr2[index]);
   
console.log(changedObjects);

I trust this explanation proves beneficial to you!

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

Implement functionality in Angular to perform tasks when the page is reloaded

I need to perform certain actions in Angular when the page is reloaded, such as adding items to local storage before the page loads and removing items after the page has fully loaded. In other words, I want to execute some tasks both before and after refr ...

Retrieving a portion of a file using Jquery ajax

I am struggling with extracting specific content from loaded data using the following simple sample code: $.ajax({ url: 'demo2.htm', success: function(loadeddata){ $("#loaded_data").after(loadeddata); alert('success'); }, ...

What is the process to enable mandatory validation after a change in input in Angular 4?

Currently, I am working on a project using Angular 4. One of the tasks I need to achieve is validation. <input [(ngModel)]="someModel" required placeholder="some placeholder"/> The validation triggers immediately, but I want it to only trigger aft ...

What is the best way to locate all mesh faces that are being lit up by a SpotLight

I am working with a THREE.Mesh that consists of a THREE.BufferGeometry containing "position" and "normal" THREE.BufferAttributes. This mesh is being lit by a THREE.SpotLight (which is a cone-shaped light source). Is there a method to ...

The Typescript module in question does not contain any exported components or functions related to

I've encountered an unusual issue while working on a React, Redux TypeScript application. It seems that after making some changes, one of the modules has stopped exporting its members. Here is the folder structure: src |---- components |---- contain ...

The app constantly requests permission for geolocation services

While experimenting with the geolocation API, I encountered an issue where my page kept repeatedly asking for permission upon refresh. To work around this problem, I attempted to save my coordinate data to local storage but encountered difficulties in ma ...

Exploring the Interaction of HashLocationStrategy and Query Parameters in Angular 4

I have an existing Angular 4 app that I am currently in the process of migrating from PathLocationStrategy to HashLocationStrategy. The goal is to switch over while keeping the entry point URL operational. Currently, the URL looks similar to this: www.test ...

Angular functions are executed twice upon being invoked within the html file

I decided to kick-start an Angular project, and I began by creating a simple component. However, I encountered a perplexing issue. Every time I call a function in the HTML file from the TypeScript file, it runs twice. TS: import { Component, OnInit } from ...

How can I eliminate the blinking cursor that appears after selecting an option from a dropdown using ng-select in Angular?

When using ng-select in Angular 5 for dropdowns, I have encountered an issue where the blinking cursor position does not behave as expected. After selecting an option from the dropdown, the cursor jumps to the start of the text instead of remaining at th ...

The specified module could not be located:

Just starting out with Vue.js, I stumbled upon a Medium article about the MEVN architecture. Here's a snippet of code from a component that I've been working on for the past two days: <template> <div class="post"> <h ...

Learn how to manipulate data within a MongoDB database schema using Node.js and Mongoose: inserting, saving, and updating records

When inserting data into the MongoDB schema presented below, make sure that Employee name, Project name, and client name can be the same, but the employee ID must be unique. Duplicate entries are not allowed. var StatusSchema = new mongoose.Schema({ ...

What is the best way to sum up array elements until they equal a target number, and then create objects using these summed values?

Suppose I have an array containing 5 different values for width, with a maximum width of 6 that needs to be reached. How can I iterate through the array and construct an object with those values each time it hits the maximum value without exceeding it? Le ...

Is there a way to transmit a div using Node.js?

Scenario: I am developing a web application that allows users to draw on a canvas, save the drawing as an image, and share it with others using Node.js. Current Progress: Drawing functionality (real-time updates on both clients). Saving the canvas as a ...

Retrieve a result from an observable within a function

While attempting to solve what appears to be a simple problem, I'm struggling to find any solutions in my research. The issue arises when trying to subscribe to an Observable within a method and return a value from it. Here is an example of what I h ...

Frustrated with the endless page loading caused by three.js

I've been trying to incorporate three.js code to showcase a 3D model in GLTF format, but my webpage keeps getting stuck on pre-loading. I need assistance with displaying a preloading page until all the files are fully loaded. Any help in resolving th ...

getting rid of the angular hash symbol and prefix from the anchor tag

I am having difficulty creating a direct anchor link to a website. Whenever I attempt to link to the ID using: where #20841 is my anchor tag. Angular interferes with the URL and changes it to: This functions properly in Chrome and Firefox, but i ...

Give a discount to each object in an array based on whichever object has the highest paid value in the loop

In my array of objects, each object has a key paid. I am looking to apply a discount to all objects except for the one with the highest paid value using a loop. var booking = [ {id:1,paid:200,currency:'USD'}, {id:2,paid:99,currency:'USD&apos ...

Module 'serviceAccountKey.json' could not be located

I'm encountering an issue while trying to incorporate Firebase Functions into my project. The problem lies in importing the service account key from my project. Here is a snippet of my code: import * as admin from 'firebase-admin'; var ser ...

The error message "E/Web Console(8272): Uncaught ReferenceError: functionName is not defined:1" popped up when trying to load web views within a

I'm working on incorporating webviews into a view pager. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = null; v = inflater.inflate(R.layout.webview_l ...

Incorporating XMLHttpRequest in my React Typescript App to trigger a Mailchimp API call, allowing users to easily sign up for the newsletter

My website needs to integrate Mailchimp's API in order for users to subscribe to a newsletter by entering their email into a field. I am looking to implement this without relying on any external libraries. To test out the functionality, I have set up ...