Filter 2 arrays to see if there is a duplicate

Im wondering how you compare 2 arrays to see weather or not there is a duplicate within that array

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

What ive tried just returns the entire array back to me which i dont want I just want to see is there a duplicate yes -> do something no -> Dont

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

It either returns the entire special range or daymonth depending what the leading argument is I just want a simple true/false equivalent if there is a duplicate

Both arrays are formatted to have similar values despite being of type Any
This is just for practical learning purposes at the moment

the values always follow something like "1201,1202,1203,1204" So MM/DD

Edit for Pyth:

On test:

dayMonth = 1215,1216

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

Adapted method:

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

    }

Result => False/False

for some reason my console doesnt log anything when I use console.log

5 thoughts on “Filter 2 arrays to see if there is a duplicate”

  1. I have no doubt that there are better ways to do this, but here’s a quick and dirty way:

    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) {
        // If value in arr2 it's a duplicate, if not, it's unique
        if (arr2.includes(v)) {
            duplicates.push(v);
        } else {
            unique.push(v);
        }
      }
      for (let v of arr2) {
        // If value isn't a duplicate, it's unique
        if (!duplicates.includes(v)) {
          unique.push(v);
        }
      }
      console.log("Duplicates: ", duplicates);
      console.log("Unique: ", unique);
      return {duplicates: duplicates, unique: unique}
    }
    filter_duplicates(a1, a2);
    Reply
  2. let result = this.specialRange.filter(o1 => dayMonth.some(o2 => o1 === o2));
    

    This will results into duplicate items ..you can simply check length of result array ..if array.length > 0 then return true else false

    Reply

Leave a Comment