2

I have an array like this:

var myObjArray = [{city: 'milwaukee', state: 'wi'}, 
                  {city:'madison', state: 'wi'}, 
                  {city:'greenbay', state: 'wi'}, 
                  {city:'madison', state: 'wi'}];

How would I compare the array against itself to find duplicates.
(Note: I need to keep the duplicates, so maybe I could add a property to the object as a flag).

contactmatt
  • 18,116
  • 40
  • 128
  • 186
  • 1
    See this post in comparing objects: http://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript – Niels Jan 30 '13 at 18:41
  • Do what @Niels suggested (there's also this post - http://stackoverflow.com/questions/1068834/object-comparison-in-javascript) and then just loop through your array and compare the objects – Adam Jenkins Jan 30 '13 at 18:45

1 Answers1

2

How about something like:

var bucket = {};
for(var i=0;i<array.length;i++) {
    var item = array[i];
    var hash = JSON.stringify(item); //or some a hashing algorithm...
    var prev = bucket[hash];
    if(prev) {
        prev.duplicate = item.duplicate = true;
    } else {
        bucket[hash] = item 
    }   
}

Or same without dependending upon JSON.stringify:

var markDuplicates = function(array, hashFunc) {
    var bucket = {};
    for(var i=0;i<array.length;i++) {
        var item = array[i];
        var hash = hashFunc(item);
        var prev = bucket[hash];
        if(prev) {
            prev.duplicate = item.duplicate = true;
        } else {
            bucket[hash] = item 
        }   
    }
    return array;
};

markDuplicates(yourArray, function(item) { return item.city + item.state; });
jevakallio
  • 35,324
  • 3
  • 105
  • 112
  • You don't want to `Stringify` it, not all browsers support this yet + You don't know the property order. This can also be different per browser. – Niels Jan 30 '13 at 18:42
  • @Niels, good points. In my defense I live in a world where JSON.strinfigy is granted. Added an alternative implementation with a safer hash function. – jevakallio Jan 30 '13 at 18:53
  • Yeah at my job we still support IE7-8, so this isn't an option for us yet =(. – Niels Jan 30 '13 at 18:56