Find the unique elements in two JavaScript arrays by comparing them and removing any duplicate

Looking to compare two arrays - one old and one new. The initial data set includes:

[
  {"member_name":"Test1","item":"Sword"},
  {"member_name":"Test2","item":"Sword"}
]

The updated set now includes:

[
  {"member_name":"Test1","item":"Sword"},
  {"member_name":"Test2","item":"Sword"},
  {"member_name":"Test1","item":"Shield"}
]

Test1 has acquired a new item. I've attempted various methods to compare these arrays without success.

Methods attempted:

This method returns the entire array, not individual items:

Items_Curr.filter(function(item) { return !Items_Prev.includes(item); });

This method results in 3 undefined values:

Items_Curr.map(e => { e.member_name });

I have been searching for a solution, but most advice addresses simpler array comparison scenarios.

For example: [a,b] - [a, b, c]

Update:

The objective is to create a new 'NewItems' array that will include all newly added names and items. Any changes should be broadcasted, otherwise ignore until the function is run again.

Answer №1

Practically speaking, it is advisable to approach the problem in this manner:

[a, b, c] - [a, b] 

This operation will result in c. To accomplish this task, you can utilize the .some method, which provides a way to customize the includes functionality.

Refer to the example below for clarification:

const arr1 = [
  {"member_name":"Test1","item":"Sword"},
  {"member_name":"Test2","item":"Sword"}
];

const arr2 = [
  {"member_name":"Test1","item":"Sword"},
  {"member_name":"Test2","item":"Sword"},
  {"member_name":"Test1","item":"Shield"}
];

const res = arr2.filter(({member_name:a, item:x}) => !arr1.some(({member_name:b, item:y}) => a === b && x === y));
console.log(res);

Answer №2

If you always want to ensure that your properties are consistently ordered, one approach is to serialize the objects using JSON.stringify and then compare the results:

const Items_Prev = [
  {"member_name":"Test1","item":"Sword"},
  {"member_name":"Test2","item":"Sword"}
]

const Items_Curr = [
  {"member_name":"Test1","item":"Sword"},
  {"member_name":"Test2","item":"Sword"},
  {"member_name":"Test1","item":"Shield"}
]

const serialized_Items_Prev = Items_Prev.map(i => JSON.stringify(i));
const NewItems = Items_Curr.filter(i => !serialized_Items_Prev.includes(JSON.stringify(i)));
console.log(NewItems);

Answer №3

When the keys of objects remain constant and new items are only added at the end, a solution like this is necessary:

const array1 = [
  {"member_name":"Test1","item":"Sword"},
  {"member_name":"Test2","item":"Sword"}
];

const array2 = [
  {"member_name":"Test1","item":"Sword"},
  {"member_name":"Test2","item":"Sword"},
  {"member_name":"Test1","item":"Shield"}
];

const compare = (array1, array2) => {
if (array1.length !== array2.length) {
  return false;
  }
  
  for (let i = 0; i < array1.length; i += 1) {
    if (array1[i].member_name !== array2[i].member_name) {
    return false;
    }
    
    if (array1[i].item !== array2[i].item) {
    return false;
    }
  }
  
  return true;
};

console.log(compare(array1, array2));

If the order of objects changes, then it becomes necessary to implement a sorting algorithm for the array before performing the comparison.

Answer №4

To accomplish this task, you can utilize the array methods filter() and findIndex()

Filter the current array using the output of the findIndex() function applied to the previous array

var prevItems = [
  {"member_name":"Test1","item":"Sword"},
  {"member_name":"Test2","item":"Sword"}
]

var currItems = [
  {"member_name":"Test1","item":"Sword"},
  {"member_name":"Test2","item":"Sword"},
  {"member_name":"Test1","item":"Shield"},
  {"member_name":"Test2","item":"Shield"}
]

var newItems = currItems.filter(function(currItem ){
  return  prevItems.findIndex(function(prevItem){
     return prevItem.member_name ==  currItem.member_name &&
            prevItem.item == currItem.item
  }) == -1
})


console.log(newItems)

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

I am converting a class component to a functional component within a React-Redux-Firebase project

I am currently in the process of rebuilding this component. Check out the updated code here Also, take a look at the project actions script here However, I'm facing an issue with rewriting mapStateToProps and mapDispatchToProps functions. The error ...

Building an array of panels in VB.NET ASP: a step-by-step guide

Is there a way to create an array of panels in VB.net and ASP instead of manually naming each panel? Within my ASP page, there is the following code: <asp:Panel ID="Panel1" runat="server"></asp:Panel> In VB.net, I am trying to generate an ar ...

How can I fix the issue with Bootstrap4 input file upload not displaying the uploaded file name in the input field? Is there a way to

I am facing an issue in my Angular component where I have used a bootstrap 4 input file tag. After selecting a file, it does not display the selected file name in place of "choose file". Could someone please advise on how to show the selected file name in ...

Centering the scrollIntoView feature on mobile devices is presenting challenges with NextJS applications

Description While navigating on mobile browsers, I'm facing a challenge with keeping an element centered as I scroll due to the browser window minimizing. I've experimented with different solutions such as utilizing the react-scroll library and ...

Using Next.js with the Link component in a client-side component to navigate back to a different page does not properly display the

UPDATE: After some investigation, I finally identified the issue. It turns out that I mistakenly wrapped my subpages return elements into the main layout component. Thank you all for your input! Currently, I am facing a challenge with the Link component i ...

Inject the code snippet from CodePen into a WordPress webpage

I have a WordPress page where I want to integrate the HTML, CSS and JS code from my Codepen project. The styling appears to be working correctly, but the JavaScript is not functioning as expected. You can view the page here: Could someone assist me in pr ...

The mysterious entity lurking within the depths of Java Script Ionic framework, forever

For my Ionic framework iOS and Android Media service, I used the Cordova Media plugin. When initializing and playing a media object in JavaScript, I encountered an undefined object error. var self = { 'currentTrack': null, 'initPlayer&apos ...

Comparing parameters between two functions in Javascript: a step-by-step guide

I am currently working on solving this problem: var name; var totalScore; var gamesPlayed; var player; var score; // Creating the game player object function makeGamePlayer(name, totalScore, ga ...

Discover the steps to convert an image to base64 while circumventing the restrictions of the same-origin policy

I've been struggling to convert an image link to base64 in order to store it on the client-side browser (IndexedDB). Despite searching for a solution for days, I have not been able to find one that addresses my issue. While I can successfully convert ...

Utilizing URIs as identifiers for GUI components in react.JS

I am looking to develop a front end using React.js where I can pass URI as name/id properties to GUI components. My goal is to then map these URI keys to corresponding values. When the web page is requested, it should display the mapped value. <input t ...

Coordinating numerous AJAX requests in Angular with the help of Restangular

I am currently working on an Angular application that relies on $scope references to update the view using a factory singleton that exposes model and state objects. The challenge I face is ensuring that multiple AJAX calls (using Restangular) made by the f ...

Retrieving the contents of a unique 404 error page using ajax

Currently attempting to retrieve the content of a custom 404 page through ajax (I need to extract a counter value from this page using Greasemonkey). Regrettably, jQuery's .fail method in ajax does not provide the option to access the page's con ...

What sets npx apart from npm?

As someone who is new to React, I recently began exploring the platform and found that Facebook offers a convenient way to kickstart a project by providing a pre-made project. To install this starter project, all I have to do is run npx create-react-app m ...

Sharing a collection of data fields

I am dealing with dynamic fields within a Bootstrap three form that is divided into tabs. Due to the removal of form tags in the modal, I have my fields set up outside. I can successfully post the values using jQuery attribute selectors like $("input[name ...

An uncaught error occurred in ReactJs while trying to read the property 'map' of an undefined variable within the {Component} component

As I pass my array to the props of the sidebar component and try to access it in my child component... After saving the code and checking the browser, an error message pops up: https://i.stack.imgur.com/6cPY8.png import React, { Component } from 're ...

Executing specific rendering procedures based on conditions for mapped data - React

When I map data in the returned render, can I then perform a conditional check on that mapped data? export default function App() { const prod = [ {'name': '1'}, {'name': '2'}, {'name': ' ...

Utilizing JavaScript to dynamically set a CSS file from an API in AngularJS

I am currently facing an issue with integrating a CSS file returned by an API into my entire website. Since the URL of the CSS file keeps changing, hard coding the URL is not feasible. While I have successfully implemented this on 'view1', my goa ...

Observing Array behaviors in TypeScript

Struggling to generate an observable from an array due to the recurring error message (A tuple type element list cannot be empty). Despite multiple attempts, I'm unable to resolve this issue. listDonationsHistory(): Observable<[]> { const ...

Choose HTML elements

Can anyone help me find an element and extract a complete block of HTML? I attempted the following: $(this).find('h1').html(); However, I only managed to retrieve the text within the h1 tag... What could I be overlooking? ...

R Web Scraping: Navigating Dynamic Web Pages with AJAX Button Clicks

Is there a way to modify the R code below in order to extract Quarterly data? I am attempting to retrieve data from Yahoo Finance, which is a dynamic web page using AJAX, resulting in the same address for both Annual and Quarterly data. The selector to u ...