Verify if two arrays of objects demonstrate unique distinctions within the latter

My task involves working with two arrays of objects, each containing a unique property id that corresponds to a filterID retrieved from a dynamoDb database. The goal is to extract the objects that have different values associated with the same id.

const firstArray = [
    {
        1234: "food"
    },
    {
        5678: "animal"
    },
    {
        4444: "car"
    }
]

const secondArray = [
    {
        1234: "food"
    },
    {
        5678: "bread"
    },
    {
        4444: "car"
    }
]

const findDifferentObjects = () => firstArray.filter(object1 => {
    return !secondArray.some(object2 => {
        return object1 === object2
    })
})
 console.log(findDifferentObjects())

Basically, what I'm aiming for is to obtain:

const different = [
    {
        5678: "animal"
    },
]

I have experimented with different approaches, similar to the example provided, but haven't been successful yet.

Answer №1

Almost there, just remember to extract the object key and then compare the values, rather than comparing the object references directly.

const filterObjects = () => data.filter(obj1 => {
    return !anotherArray.some(obj2 => {
        const key = Object.keys(obj1)[0];
        return obj1[key] == obj2[key];
    })
})
console.log(filterObjects())

Answer №2

try using the following code snippet:

const filterObjects = () =>
  data.filter((obj1) => {
    return !temp.some((obj2) => {
      return JSON.stringify(obj1) === JSON.stringify(obj2);
   });
  });
console.log(filterObjects());

When comparing objects, remember they are stored in different locations in memory. To properly compare them, compare their properties or convert them to strings and then compare.

Answer №3

let numbers = [
    {
        1234: "fruit"
    },
    {
        5678: "pet"
    },
    {
        4444: "vehicle"
    }
]

let words = [
    {
        1234: "fruit"
    },
    {
        5678: "dog"
    },
    {
        4444: "car"
    }
]

const findDifferentItems = (arr1, arr2) => {
   let result = arr1.filter(item => {
     return Object.keys(item).some(key => {
       return arr2.some(compare => {
         return (compare[key] && item[key] !== compare[key]);
       });       
     })
   });
   return result;  
}

const updatedItems = findDifferentItems(numbers, words);
console.log(updatedItems);

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

Error encountered while attempting to cast value "xxxxxx" to ObjectId in the "item" model, resulting in a CastError

I've been struggling to resolve an error while trying to delete a todo from a page using findByIdAndRemove and findByIdAndDelete methods. Despite researching and attempting various solutions, the error persists. Any assistance would be greatly appreci ...

Sending multiple forms at once with a single submission

I've been racking my brain trying to determine the feasibility of a particular task. I am currently utilizing zen-cart as my shopping cart software, but what I really want to achieve is creating a hardcoded page featuring a list of 7-9 products. Each ...

Expressjs Error- ReferenceError: cors has not been defined in this context

While working on creating a backend using ExpressJs, I encountered an error when running the backend. app.use(cors()) ^ ReferenceError: cors is not defined at Object.<anonymous> (C:\Users\hp\Desktop\Entri\kanba\ ...

Is there a problem with renaming files using the multer module's filename options?

I can't figure out why this isn't functioning as intended. The file upload feature is operational, but the generated name consists of a long string like 04504a8b6c715f933110c8c970a8f6ad. What I need is for the filename to include the original nam ...

What is the best way to link one element to another element?

Apologies for the mismatched title, but here's my issue: I need to create hidden checkboxes for each Polymer's paper-button div in jsp/style related problems. <%int i; %> <form ACTION="Computation.jsp"> <% for(i=0; i<n; ...

Implementing NodeJS to showcase an array of items - the step-by-step guide

I'm currently setting up a webpage to display a list of books using NodeJS, but despite my efforts, the page remains blank when I launch it. My goal is to showcase the array of books on the page, and so far, here's the code that I have written. A ...

Design a customizable overlay with a moveable and size-adjustable layer below it

After working with kineticjs, I successfully created an app that allows images to be draggable and resizable, which is great progress; Now, I am facing a challenge: I want to have an overlay in the center with a block of variable height/width that display ...

At what point does the constructor of an injected service in Angular execute?

When using @Injectable({providedIn: 'root'}) in Angular 7 for a service, the constructor of the service executes when exactly? Is it upon the creation of a component that utilizes it as a dependency or does it wait until a method within the servi ...

JavaScript implementation of a carousel slider with responsive design

I have successfully implemented a feature carousel slider using the jquery.featured.carousel.js file along with some CSS. Here is the jsfiddle link to my project: LINK. When running this code on localhost, I noticed that I need to refresh the page every ...

Send a triggering function to two separate components

My objective is as follows: render() { return ( <div> <Child onTrigger={xxx} /> <button onClick={xxx} /> </div> ) } Upon clicking the button, I wish for some action to take place in ...

Javascript functions fail to execute as intended

I have a project called calc, which includes various functions such as init. Within this project, there are three buttons that I am adding to the div using jquery. When a user clicks on any of these buttons, it should trigger the inputs function. Based on ...

The optimal and most secure location for storing and retrieving user access credentials

After receiving a list of locations accessible to the session user from the server, I am seeking the ideal location to store these roles in Angular. This will allow me to determine whether or not to display specific routes or buttons for the user. Where ...

The client using socket.io is receiving events for "double plus one"

While experimenting with socketio, I encountered a bug that others are experiencing as well but I haven't been able to find a valid solution. This is the server-side code: const app = require('express')(); const server = require('http& ...

"Enhancing Code Functionality in React - Seeking Ways to Improve

When working with Redux, I often find myself repeatedly using the same piece of code: const dispatch = useDispatch() Then, every time I need to call a function, I do something like this: dispatch(endpointError(true)) My goal is to streamline this proce ...

ng2-idle server side rendering problem - Uncaught ReferenceError: document is undefined

Can ng2-idle be used for idle timeout/keepalive with pre-rendering in Angular 4? I followed this link for implementation: It works fine without server pre-rendering, but when I add rendering back to my index.html, I keep getting the following error: Exce ...

Utilizing Arrays in Typescript within the Angular Framework

I have developed a Rest API that provides data to populate two drop-down lists in a form. The information retrieved from the API is grabbed by the Angular backend and assigned to the respective drop-downs. Rather than making separate Get requests for each ...

Is it possible to select a file name at random from an array in Processing 2?

I'm currently working on a project in Processing where I need to randomly select a document and print it from the terminal. Specifically, I am having trouble figuring out how to store filenames in an array and then have Processing choose one at random ...

Adding property to an object retrieved from an API in a React application can be achieved effortlessly by utilizing the useState

How can I implement a toggle functionality for Bookmarked Meals on my Meal Recipe Website available at ? I am currently using the logic to set data.meals[0].bookmarked to true or false, but I want to use setState instead in order to rerender the page when ...

Having trouble rendering an object in my ThreeJS project. The error message says: "THREE.OBJLoader: Unexpected line: 'usemap glass'"

I encountered an error while running threejs in an angular 8 application. The objective is to load an object, for which the object and material files were obtained from Kenney assets. Despite referencing examples on the official threejs site and other onli ...

React with Typescript: It appears that you are attempting to utilize Typescript without having it properly installed on your system

I am embarking on creating a React application integrated with TypeScript. Initially, I visited the React website to seek guidance on incorporating TypeScript in my project. The website directed me to execute the following command in the terminal: npx crea ...