Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicate element pairs from multidimensional array

I have an array that looks like this:

1.  coordinates = [ [16.343345, 35.123523],
2.                  [14.325423, 34.632723],
3.                  [15.231512, 35.426914],
4.                  [16.343345, 35.123523],
5.                  [15.231512, 32.426914] ]

The latitude on line 5 is the same as on line 3, but they have different longitudes and are therefore not duplicates.

Both the latitude and longitude are the same on line 3 and 6, and are therefore duplicates and one should be removed.

like image 953
holyredbeard Avatar asked Jan 19 '13 15:01

holyredbeard


2 Answers

The difficulty in this question that different arrays never compare equal even if they contain same values. Therefore direct comparison methods, like indexOf won't work.

The following pattern might be useful to solve this. Write a function (or use a built-in one) that converts arrays to scalar values and checks if these values are unique in a set.

uniq = function(items, key) {
    var set = {};
    return items.filter(function(item) {
        var k = key ? key.apply(item) : item;
        return k in set ? false : set[k] = true;
    })
}

where key is a "hash" function that convert items (whatever they are) to comparable scalar values. In your particular example, it seems to be enough just to apply Array.join to arrays:

uniqueCoords = uniq(coordinates, [].join)
like image 199
georg Avatar answered Oct 07 '22 09:10

georg


You can use standard javascript function splice for this.

for(var i = 0; i < coordinates.length; i++) {
    for(var j = i + 1; j < coordinates.length; ) {
        if(coordinates[i][0] == coordinates[j][0] && coordinates[i][1] == coordinates[j][1])
            // Found the same. Remove it.
            coordinates.splice(j, 1);
        else
            // No match. Go ahead.
            j++;
    }    
}

However, if you have thousands of points it will work slowly, than you need to consider to sort values at first, then remove duplicates in one loop.

like image 43
SergeyS Avatar answered Oct 07 '22 10:10

SergeyS