Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    May 2004
    Posts
    391
    Thanks
    76
    Thanked 0 Times in 0 Posts

    remove duplicates from 2 arrays

    I would like to remove duplicates from 2 arrays where if one exists in the other remove it. So for the 2 arrays below "myArray1" should now only have "red" and "orange" in the array and myArray2 should only have "purple" and "black" in the array. Please help.

    myArray1 = new Array("blue","red", "green", "orange")
    myArray2 = new Array("blue","green", "purple","black")

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,969
    Thanks
    56
    Thanked 557 Times in 554 Posts
    you can try this (you will need to shim an indexOf array method if you want to support older IE):
    Code:
    var array1 = ["blue","red", "green", "orange"];
    var array2 = ["blue","green", "purple","black"];
    var count = array1.length-1;
    for (var i = count; i--;) {
    
    if (array2.indexOf(array1[i]) !== -1){
    array2.splice(array2.indexOf(array1[i]),1);
    array1.splice(i,1);
    }
    
    }
    console.log(array1);
    console.log(array2);

  • Users who have thanked xelawho for this post:

    nikko50 (06-05-2014)

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,035
    Thanks
    203
    Thanked 2,539 Times in 2,517 Posts
    If you only want to remove the duplicates from the second array simply comment out the line array1.splice(i,1);

    You can make it case-insensitive with

    myArray1=myArray1.join('|').toLowerCase().split('|'); // to make case insensitive
    myArray2=myArray2.join('|').toLowerCase().split('|'); // to make case insensitive
    Last edited by Philip M; 06-05-2014 at 08:52 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    nikko50 (06-05-2014)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •