Check for duplicates within 2 arrays by implementing a filtering process

I am trying to figure out how to compare two arrays to determine if there are any duplicates within them.

 const result = this.specialRange.filter(d => !dayMonth.includes(d));

What I have attempted so far just returns the entire array back to me, but I only want to know if there is a duplicate: yes -> do something, no -> don't do anything.

   var dayMonth: any[] = ["1201","1202","1203","1204","1205"];
   specialRange: any[] = ["1201","1202","1203","1204"];

Depending on the leading argument, it either returns the entire special range or dayMonth, but I simply want a true/false result if there is a duplicate.

Both arrays have similar values, even though they are of type Any. This is just for practical learning purposes at the moment.

The values always follow a format like "1201,1202,1203,1204" representing MM/DD.

Update for Pyth:

When testing:

dayMonth = 1215,1216

specialRange =

1215,1216,1217,1218,1219,1220,1221,1222,1223,1224,1225,1226,1227,1228,1229

Modified method:

for(let v of dayMonth){
      if(this.specialRange.includes(v)){
        alert('true');
      }
      else{
        alert('false')
      }

    }

Result => False/False

For some reason, my console does not log anything when I use console.log.

Answer №1

Although there may be more efficient methods, here's a simple way to tackle this problem:

const a1 = [1200, 1201, 1202, 1203];
const a2 = [1202, 1203, 1204];
// Expected Duplicates: [1202, 1203]
// Expected Unique: [1200, 1201, 1204]


function filter_duplicates(arr1, arr2) {
  let duplicates = [];
  let unique = [];
  for (let v of arr1) {
    // Check if value in arr2, classify as duplicate or unique
    if (arr2.includes(v)) {
        duplicates.push(v);
    } else {
        unique.push(v);
    }
  }
  for (let v of arr2) {
    // Add unique values from arr2
    if (!duplicates.includes(v)) {
      unique.push(v);
    }
  }
  console.log("Duplicates: ", duplicates);
  console.log("Unique: ", unique);
  return {duplicates: duplicates, unique: unique}
}
filter_duplicates(a1, a2);

Answer №2

const filteredResult = this.specialRange.filter(item1 => dayMonth.includes(item1));

After filtering, there may be duplicate items. To check for duplicates, simply compare the length of the filtered result array. If the length is greater than 0, return true, otherwise return false.

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

Effective approach to exchange information among controllers in AngularJS

There are numerous techniques available to share data between controllers in Angular, such as accessing prototypical data from a parent scope, utilizing scope events for controller communication, or implementing shared services. However, what is considere ...

Exploring the limitations of middlewares in supporting independent routers

When I examine the code provided, it consists of three distinct routers: const Express = require("express") const app = Express() // Three independent routers defined below const usersRouter = Express.Router() const productsRouter = Express.Router() cons ...

Is it possible to run two commands in npm scripts when the first command initiates a server?

When running npm scripts, I encountered an issue where the first command successfully starts a node server but prevents the execution of the second command. How can I ensure that both commands are executed successfully? package.json "scripts": { "dev ...

Error encountered: Circular reference issue was encountered when attempting to retrieve navigator.plugins with the use of Selenium and Python

I'm attempting to access the value of navigator.plugins from a Selenium-driven ChromeDriver initiated google-chrome Browsing Context. Using google-chrome-devtools, I am able to retrieve navigator.userAgent and navigator.plugins as shown below: https ...

Using JavaScript to toggle the visibility of grids depending on the radio button choice and then triggering this action by clicking on the search button

As a newcomer to AngularJS development, I am encountering some challenges while attempting to implement the following scenario. Any suggestions or guidance would be greatly appreciated. I aim to showcase either one or two Angular UI grids based on the rad ...

How to pass data/props to a dynamic page in NextJS?

Currently, I am facing a challenge in my NextJS project where I am struggling to pass data into dynamically generated pages. In this application, I fetch data from an Amazon S3 bucket and then map it. The fetching process works flawlessly, generating a se ...

Removing an element with a specific class that was created with Javascript can be done by clicking outside the box

I needed to eliminate an element that was created using JavaScript of a specific class when clicked outside the box. I have created a color-picker using .createElement and added a class to it. Now, my goal is to remove that picker whenever a click occu ...

What are the steps to successfully launch a Node.js / Express application with typescript on heroku?

I attempted to deploy my node.js / express server app on Heroku but encountered some issues. I followed the steps outlined in a blog post, which you can find here. Unfortunately, the deployment did not succeed. Below are snippets of the code from my serve ...

The Angular 2 service is not transmitting the POST data in the correct format, although it functions properly when transmitted through PostMan

When the POST data is transmitted from the Angular 2 service in this manner: const data = new FormData(); data.append('date', '12/01'); data.append('weight', '170'); return this.http.post(this.u ...

The jQuery validation feature is failing to function properly within a bootstrap modal

I'm facing an issue with the jQuery validation plugin in my express app sign-up form that uses Bootstrap for the front-end. Despite setting rules and messages for name, email, and phone number fields, the validation is not functioning correctly. Below ...

Dealing with Unexpected Timeout Errors and Memory Leaks in Express/Typescript Using Jest, Supertest, and TypeORM

Currently, I am in the process of writing unit tests for an express API. Each test suite initiates a fresh instance of an express server before running the tests. Individually, each test suite runs smoothly without any problems. However, when executed tog ...

Are there differences in alignment?

I'm looking to create a unique visual effect where text is aligned differently on each line, shifting left, right, center, or wherever else, with the alignment origin varying by just a few pixels. This would be perfect for adding some visual interest ...

Using AngularJS to inject a variable into the standard filter

Currently, I am attempting to develop a custom filter that mimics the functionality of the standard Angular filter in HTML, with the distinction that it accepts a variable as input rather than a fixed value. For instance, within my html document, you may ...

Wrap the words around to fit a rectangle with a specific ratio, rather than a specific size

Does anyone have a solution for breaking text at word boundaries to perfectly fit a rectangle with a specific approximate ratio, such as 60:40 (width:height)? Please note that this is not just about setting a width limit (e.g. 80 characters or 600px) and ...

Tips for modifying the type definition of a third-party library in a Vue project built with Create-Vue

After updating the Cesium library in my Vue project, I encountered some errors. This is the code snippet: camera.setView({ destination, orientation: { heading, pitch } }) The error message reads: Type '{ heading: number; pitch: number; }' i ...

The mouse event listener fails to function in plain JavaScript

I've been tackling a fun little project from The Odin Project called "ETCH-A-SKETCH". The idea is to change the color of squares when the mouse hovers over them, but I'm having trouble getting the onmouseover event to trigger. Any idea what could ...

The boolean type in TypeScript is throwing an error because it does not have any call

Currently, I am grappling with an issue in my Typescript and React Native project. The error message displayed on the console reads: "This expression is not callable. Type 'Boolean' has no call signatures." My code consists of a simple home page ...

Utilizing a custom filter for object manipulation within Vuetify's v-autocomplete

When using vuetify v-autocomplete with an object where the object consists of Key-Value pairs, the search functionality is based on the item-text. In my example, I am displaying the object as {1200-Chloride Systems}. Is it possible to make the search funct ...

Having trouble establishing a connection with the SignalR client using an npm package

Greetings! I am looking for npm packages that can help me run SignalR client on my console. I've attempted using the following package - https://www.npmjs.com/package/signalr-client, but unfortunately, it is not establishing a connection to the server ...

What is the best way to generate a one-level breadcrumb using Jquery?

In certain applications, I am interested in implementing a single-level breadcrumb trail that looks like this: Home -> Product -> Applications -> Application 1 Since 'Applications' can have several children, I want to incorporate a dro ...