简体   繁体   中英

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 .filter() to get rid of partial duplicates (only matching the colors)?

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

I would use a for loop to populate a new, unique array:

var old_array = [[1, red], [2, green], [3, red], [3, blue], [5, green]],
    old_count = old_array.length,
    unique_array = [], check_array = [], i = 0;

for(; i < old_count; i++) {
    if (check_array.indexOf(old_array[i][1]) === -1) {
        check_array.push(old_array[i][1]);// this array is filled with new colors, and used for checking
        unique_array.push(old_array[i]);
    }
}

You could use a hash table with the color and use Array#filter for the wanted items.

 var data = [[1, 'red'], [2, 'green'], [3, 'red'], [3, 'blue'], [5, 'green']], result = data.filter(function (a) { if (!this[a[1]]) { return this[a[1]] = true; } }, Object.create(null)); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

// 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.

I would just keep track of the unique colors in an object passed into the filter, because as a hash it's guaranteed to be unique. If the object doesn't have a property by that color name, it returns it from the filter. Otherwise if it does it ignores the item.

var colors = [[1, "red"], [2, "green"], [3, "red"], [3, "blue"], [5, "green"]];

var uniqueArray = colors.filter(function(item, pos) {
    if (!this.hasOwnProperty(item[1])) {
        return this[item[1]] = true;
    }
    return false;
}, {});

This gives you uniqueArray = [[1,"red"],[2,"green"],[3,"blue"]] , as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM