Does _.difference compare objects by their references or by each property individually?

I have two arrays that I need to compare and ensure they are not equal in terms of their content (property by property).

The arrays and their current values can be seen in the image provided.

Can you recommend a lodash function or JavaScript function that can check for deep equality while excluding the $$hashkey of the arrays?

https://i.sstatic.net/9yY15.png

Answer №1

AngularJS offers a method to compare the equality of two objects without using lodash or pure javascript: angular.equals. You can use it like this:

angular.equals(newValue, oldValue);

Since this method is specific to AngularJS, it handles issues like $$hashkey automatically (by ignoring it). Additionally, it compares property values one by one with type checking included.

Check out this Plunker example for reference.

Answer №2

If you want to compare objects in an array, you can utilize the _.isEqual function from Lodash. This function thoroughly checks all properties of the objects.

var obj = [{ 'a': 1, b: 2 },{ 'a': 3, b: 4 }];
var other = [{ 'a': 1, b: 2 }, { 'a': 3, b: 4 }];

_.isEqual(obj, other); // => true

Keep in mind that the order of elements in both arrays is crucial. For example, this will result in false:

var obj = [{ 'a': 1, b: 2 },{ 'a': 3, b: 4 }];
var other = [{ 'a': 3, b: 4 },{ 'a': 1, b: 2 }];

_.isEqual(obj, other); // => false

UPDATE

Although _.isEqual requires arrays to be in the same order for comparisons, you can use another lodash function like sortBy to handle this issue as shown below:

_.isEqual(_.sortBy(obj, 'id'), _.sortBy(other, 'id'));

This approach sorts the arrays by id first before checking their equality. You can also sort by multiple properties or a custom function if needed.

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

Multiple uses of p-fileUpload in primeng are not functioning as expected

Let me explain the situation with this component. I have defined it as follows: <p-fileUpload #fileUpload accept=".csv,.txt" maxFileSize="1000000" customUpload="true" (uploadHandler)="uploadFile($event)"> In my package Json file, I have specified: ...

Using jasmine with Array.from is not a compatible combination

Attempting to utilize Jasmine for testing my code has presented a challenge. The code functions properly in the browser, and Array.from() also works seamlessly in node, as demonstrated below: > t = [1, 2, 3] [ 1, 2, 3 ] > Array.from(t) [ 1, 2, 3 ] ...

Create directories in a nested structure using a multi-level JSON object with async.js

DEFINITION NewMethod#generateDirectoriesFromJSON (data, cb); data: JSON object. cb: Callback function. Parameters: err (Error), directoriesCreated (Boolean, true if at least one directory has been created). Assuming that the NewMethod class includes a ...

Exploring the principles of object-oriented design within the context of Node

I am facing challenges with the asynchronous flow of Node.js. Let's assume we have the following class: function myClass() { var property = 'something'; var hasConnected = false; this.connect = function(params) { // Logic to conn ...

JavaScript closures and the misinterpretation of returning values

function generateUniqueCelebrityIDs(celebrities) { var i; var uniqueID = 100; for (i = 0; i < celebrities.length; i++) { celebrities[i]["id"] = function () { return uniqueID + i; }; }; return celebrities; ...

The script tag in NextJS is not properly loading the Amplitude library

I am facing an issue with loading events using Amplitude JS for tracking, despite having the correct code in place. Here is the code snippet that I used: import Document, { Html, Head, Main, NextScript } from 'next/document'; import Script from & ...

I'm experiencing an issue where the graph seems to vanish whenever I dynamically add edges using vis-network.js. What could

I've encountered a strange issue in my Vue project while using vis-network.js - the graphics disappear when I dynamically add edges, but dynamic updates and deletes work fine. To further investigate, I created a test page where I included vis-network ...

"Utilizing ng class with an array of objects: A step-by-step guide

I am facing a scenario in which my response appears as follows: "currency" : [ { "_id" : ObjectId("584aad5d3e2537613e5f4c39"), "name" : "USD" } ], I need to enable my checkbox based on the currency name. I attempted the followi ...

Error in NodeJS Mongoose: Undefined value causing inability to call the 'toString' method

I am having an issue with displaying the name of a Team from my database on the web page. Here is the code snippet I am using: var Team = require('../schemas/Team').Model; app.get('/match', function(req, res) { var key = 1359407087 ...

Conceal a tag only visible at specific screen sizes

Is there a way to hide the following code when the screen resolution is 1024 X 768 or lower? <!-- AddThis Button BEGIN --> <div class="addthis_toolbox addthis_default_style"> <a class="addthis_button_facebook_like" fb:like:layout="button_co ...

A fusion of Angulary and Django REST

What is the best way to filter my queryset? For instance: .controller('TViewController', ["$scope", "$stateParams", "Ad", "Banner", function($scope, $stateParams, Ad, Banner) { $scope.ad = Ad.get({ ad_id: $stateParams.ad_id }); $scope.b ...

Identify erroneous or incomplete JSON data when making an AngularJS $http.post() request

After reviewing the source code of AngularJS, it is evident that any $http.post request returning an HTTP status code in the 200-299 range will trigger the success() callback, even if the response contains invalid data such as malformed JSON. Despite sett ...

Ensuring accuracy in form submissions for the month of February

I have a .net custom validator set up to validate an input date in a form. The validation should check the number of days in February, allowing 28/02/2015 but not 29/02/2015. The C# server validation is functioning correctly with the following code snippe ...

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 ...

What steps should I take to deactivate a Survey until the video has been watched in its entirety?

We have been grappling with finding a resolution to this issue. We are clear on the solution we believe is suitable. We just lack the knowledge on how to implement it. We have six instructional videos that we want our users to view. Each video is paired ...

Storing a Class Instance in Vue Data

I am currently incorporating PDFtron into a Vue component. To display the PDF viewer iFrame upon loading the Vue, I am initializing the instance in the mounted hook: mounted() { const viewerElement = document.getElementById('viewer'); th ...

how to check if a string has white spaces in a react application

If the input string has white space, the alert will indicate unsuccessful. If the input string does not have any white space, the alert will be successful. import React from "react"; export default function DropDown() { let i = document.getEle ...

How come my MySQL date is decreasing by one day when using JavaScript?

My todo list is stored in a MySQL database with columns for todoTitle and todoDate. However, when I display the todoDate on my website, it shows the date decremented by one day. For example, if the date in the database is 2016-12-20, it will show as 2016-1 ...

Encountering an error in Strapi project: URL undefined

I am currently in the process of setting up a Strapi application and getting it up and running. Following the instructions provided in this document: After successfully setting up Strapi and creating the application, I encountered an error when trying to ...

Error encountered in React JS: The property being accessed is undefined and therefore cannot be mapped

I have been working on a MERN project and I am currently at the stage where I am integrating the frontend and backend using Axios. However, I have encountered some issues. One of the most common errors I am facing in my list screens is: TypeError: Cannot r ...