Andrea Andrea - 10 months ago 46
Javascript Question

Remove duplicates from a multidimensional array

I have found questions that kind of touch on the issue I'm having, but I haven't found a solution that works for me yet. I have this array:

[[1, red], [2, green], [3, red], [3, blue], [5, green]]
and I need it to return
[[1, red], [2, green], [3, blue]
. What I need the code to do is go through the array and find ONLY colors that match, not numbers, and get rid of that entire index.

I have tried something like this

var uniqueArray = colors.filter(function(item, pos) {
return colors.indexOf(item) == pos;

I'm thinking that this code is searching for a complete match, and I only require a partial match. So basically, how would I modify
to get rid of partial duplicates (only matching the colors)?

Please let me know if I need to provide any more information.

Answer Source
// Parameter marr: multidimensional array
function removeSameColors(marr){
    var carr = [];
    var rarr = [];
    var j = -1;

    for(var i = 0, l = marr.length; i < l; i++){
        if(carr[marr[i][1]] !== true){
            carr[marr[i][1]] = true;
            rarr[++j] = marr[i];

    return rarr;

That should solve your problem with very low execution time.