Using ES6 to Compare and Remove Duplicates in an Array of Objects in JavaScript

I am facing a challenge with two arrays:

Array One

[
  { name: 'apple', color: 'red' },
  { name: 'banana', color: 'yellow' },
  { name: 'orange', color: 'orange' }
]

Array Two

[
  { name: 'apple', color: 'red' },
  { name: 'banana', color: 'yellow' },
  { name: 'grape', color: 'purple' },
  { name: 'kiwi', color: 'green' },
  { name: 'orange', color: 'orange' }
]

I want to compare both arrays and eliminate duplicate objects from the second array like this:

[
  { name: 'grape', color: 'purple' },
  { name: 'kiwi', color: 'green' }
]

I attempted using ES6 by running this code:

const result = arrayTwo.filter((obj) => {
    return !arrayOne.includes(obj);
  });

However, the result is turning out as:

[
  { name: 'apple', color: 'red' },
  { name: 'banana', color: 'yellow' },
  { name: 'grape', color: 'purple' },
  { name: 'kiwi', color: 'green' },
  { name: 'orange', color: 'orange' }
]

I need guidance on what I am doing wrong and the best way to achieve this. In actual scenarios, both arrays contain over 10000 items.

I am not aiming for identical matches; instead, I only want to remove duplicates.

Thank you :)

Answer №1

Here is a code snippet for you to try:

obj1 = [
  { repo: 'edat-ims-github', status: 200 },
  { repo: 'edat-ims-github-spa', status: 200 },
  { repo: 'test-repo-three', status: 200 }
]

obj2 = [
  { repo: 'edat-ims-github', status: 200 },
  { repo: 'edat-ims-github-spa', status: 200 },
  { repo: 'test-repo-one', status: 200 },
  { repo: 'test-repo-two', status: 200 },
  { repo: 'test-repo-three', status: 200 }
]

filteredArr = obj2.filter(el1 => {
  return obj1.every(el2 => {
    return !(el1.repo == el2.repo && el1.status == el2.status)
  })
})

console.log(filteredArr)

The code checks if each element of obj1 is NOT present in obj2. If an element is found in obj2, it is excluded from the filteredArr. However, elements not found in obj2 are included in the filteredArr.

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

A guide to setting up application-level variables in Node.js

Currently in my project, I have over 100 cron jobs running using npm's cron package. The issue I am facing is that I need the ability to stop any cron job while it is running. The code snippet can be found in the app.js file: var jobHandler =require ...

Designing versatile buttons with HTML

When accessing the website on a phone, I have trouble seeing and tapping on these two buttons because they are too far apart. I would like to change it so that once a file is selected, the 'choose file' button will be replaced by the upload butto ...

Strategies for re-rendering a React component when the useState value remains the same or retains its previous value

I am currently using a useState hook to store the value of selectFolderId: const [selectFolderId, useSelectFolderId] = React.useState(documentStore.id) Despite trying to update selectFolderId with the new value from DocumentStore by using a useEffect hook ...

Switching the scope or zone in Angular when handling events external to Angular

Currently, I am utilizing an external library within my Angular 6 application that incorporates customizable event listeners. Specifically, I am employing flowchart.js, although similar issues may arise with other libraries. In the case of flowchart.js, i ...

What sets apart `var now = new Date();` and `var now = Date();` in JavaScript

I am specifically interested in exploring the impact of adding "new" on the variable, as well as understanding when and why it is used. I would also like to understand why I am obtaining identical answers when printing both versions. ...

Leveraging react-router for automatic redirection after form submission

My goal is to implement a search functionality on the page where users can enter a search term (name, email, username) and have the page filter out one card from all the cards based on the search value. I believe that upon pressing enter, we should redirec ...

Tips for sending parameters to XSLT using a Javascript function

Despite my efforts to find a solution in various online posts, I haven't been able to resolve the issue. The challenge lies in my HTML file that includes a JavaScript function for parsing XML and rendering XSLT. I have multiple 'records' in ...

Looking for a script to automate clicking on a specific web element using JavaScript

When working with Selenium, we utilize an action to interact with an element by clicking on it at specific coordinates (X, Y). action.MoveToElement(element, X, Y).Click().Build().Perform() I am looking to achieve the same functionality using Javascript. ...

Highcharts - resolving cross-browser e.Offset discrepancies in mouse event detection on charts

I need to determine if the mouseup event is inside the chart and display the coordinates of the point. The code works in Chrome but not in Firefox due to the lack of the event.offset property. jQuery(chart.container).mouseup(function (event) { eoff ...

The dynamic import() syntax is not compatible with the target environment, preventing the use of external type 'module' in a script

I am currently facing an issue with my React app. The command npm start is working as expected, but when I try to run npm run build, it keeps failing. It's crucial for me to run npm run build in order to deploy the app on a website. I have already sp ...

Is it possible to dynamically group by one column in a dataset without requiring a trigger function?

I've been working on a script that retrieves values from another page and organizes them into a table alphabetically by Name, City, and District. The current script is functioning well, but I now want to enhance it by grouping the values by city as we ...

Retrieving value from the parent scope using the conventional approach

Today I was puzzled by some unexpected behavior of AngularJS. While using console.log to log $scope, I noticed that there was no key attached to the scope named val1. However, when I used console.log($scope.val1), it returned a value as an object. After ...

In the past, my code would run smoothly without any issues, but now I am encountering a runtime error even though the code comp

Recently, I started learning TypeScript and encountered an issue while working with Classes. My code was functioning properly before but now it's displaying a runtime error. ...

Encountering an undefined json array when making an AJAX request

There have been numerous questions on this topic, but none of the specific solutions seemed to apply to my situation. So, I apologize if this is a duplicate query. I am currently working on fetching data from an SQL database using a PHP file that passes t ...

Make sure that the Mongoose save operation is finished before executing the callback function

Encountering a challenge in my initial node app development, where the callback function is triggered before the database write operation is fully completed. The issue arises when an authenticated user visits site.com/model URL. The system checks the data ...

What is the best way to assign a distinct index value to each object in an array

When I use the function below to add an index to each array object, all IDs end up with the same value when I check console.log: var foo = [...this.props.articleList]; foo.forEach(function(row, index) { row.id = index+1; }); console.log(foo); My des ...

Accessing the Current User Using Firebase Admin SDK in Node.js

Is there a way to retrieve the currentUser in firebase admin SDK? While in client SDK we have options like onAuthStateChanged() or firebase.auth().currentUser() When using NodeJs Server.js with firebase admin SDK, the onAuthStateChanged() method doesn&a ...

What is the best way to access and modify file information in nodejs?

I'm looking to retrieve and modify the details of a .mp4 file, specifically the Description property (Title, Subtitle, Rating, Tags, Comments). Is there a way to do this using Node.js? I understand that typically you would right-mouse click on the fil ...

Using Laravel to set cookies with Ajax

I am facing difficulties in setting cookies through laravel using ajax. Despite reading several questions and posts, I have not been able to find a solution. My issue involves a dropdown that triggers a javascript function to send its value to a controlle ...

What are the advantages of choosing Express over AngularJS?

It's clear to me that Express is typically found on the server, while Angular is usually on the client side. However, from what I've gathered, Angular has the capability to perform all the functions that Express can, such as: routing interactin ...