removing duplicates from a nested/2D array (removing the nested duplicate element)

痞子三分冷 提交于 2019-12-25 13:41:11

问题


So that:

array = [[12,13,24],[24,22,11],[11,44,55]]

would return:

cleanedArray = [[12,13,24],[22,11],[44,55]]

I'm surprised not to have found this answered here.


回答1:


var array = [[12,13,24],[24,22,11],[11,44,55]];
var output = [];
var found = {};
for (var i = 0; i < array.length; i++) {
    output.push([]);
    for (var j = 0; j < array[i].length; j++) {
        if (!found[array[i][j]]) {
            found[array[i][j]] = true; 
            output[i].push(array[i][j]);
        }
    }
}

console.log(output);



回答2:


Are you looking for a function that does this for just two-dimensional arrays? If so, then I think this would work:

Array.prototype.clean = function()
{
    var found = [];
    for(var i = 0; i < this.length; i++)
    {
        for(var j = 0; j < this[i].length; j++)
        {
            if(found.indexOf(this[i][j]) != -1)
            {
                this[i].splice(j, 1);
            }
            else
            {
                found.push(this[i][j]);
            }
        }
    }

    return this;
};

If it's just a one-dimensional array you're looking for, then:

Array.prototype.clean = function()
{
    var found = [];
    for(var i = 0; i < this.length; i++)
    {
        if(found.indexOf(this[i]) != -1)
        {
            this.splice(i, 1);
        }
        else
        {
            found.push(this[i]);
        }
    }

    return this;
};

this would work. If you're doing either of those, then do .clean() on your array to clean it up.




回答3:


A simple function that modifies the original array is:

function removeDups(a) {
  var item, j, found = {};

  for (var i=0, iLen=a.length; i<iLen; i++) {
    item = a[i];
    j=item.length;

    while (j--) {
      found.hasOwnProperty(item[j])? item.splice(j,1) : found[item[j]] = '';
    }
  }
  return a;
}


来源:https://stackoverflow.com/questions/19803539/removing-duplicates-from-a-nested-2d-array-removing-the-nested-duplicate-elemen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!