简体   繁体   English

从 JavaScript 中的二维数组中删除相似的重复项

[英]Remove similar duplicates from 2D array in JavaScript

I need to remove similar duplicates as well as real duplicates from 2D array in JavaScript.我需要从 JavaScript 中的二维数组中删除类似的重复项以及真正的重复项。

let a = [
  [5, 6],
  [1,1],
  [6,5],
  [1,1],
  [3,2],
  [2,3]
]

function makeUnique(arr) {
  var uniques = [];
  var itemsFound = {};
  for(var i = 0, l = arr.length; i < l; i++) {
      var stringified = JSON.stringify(arr[i]);
      if(itemsFound[stringified])  continue; 
      uniques.push(arr[i]);
      itemsFound[stringified] = true;
  }
  return uniques;
}

a=makeUnique(a)
console.log(a);

I have got this output:我有这个 output:

[ [ 5, 6 ], [ 1, 1 ], [ 6, 5 ], [ 3, 2 ], [ 2, 3 ] ] [ [ 5, 6 ], [ 1, 1 ], [ 6, 5 ], [ 3, 2 ], [ 2, 3 ] ]

Correct should be:正确的应该是:

[ [ 5, 6 ], [ 1, 1 ], [ 2, 3 ] ] [ [ 5, 6 ], [ 1, 1 ], [ 2, 3 ] ]

My code removes correctly duplicates, but I need to remove similar duplicates also.我的代码正确地删除了重复项,但我也需要删除类似的重复项。

For example if I have [3,2] and [2,3] I should remove [3,2] (the one which has bigger starting index value.)例如,如果我有 [3,2] 和 [2,3],我应该删除 [3,2](具有更大起始索引值的那个。)

Could you help me to fix this?你能帮我解决这个问题吗?

Here is an example of how you can do it:以下是如何执行此操作的示例:


function makeUnique(arr) {
    var uniques = [];
    var itemsFound = {};
    arr.sort((a, b) => a[0] + a[1] - (b[0] + b[1]))
    for (var i = 0, l = arr.length; i < l; i++) {
        if (!itemsFound[arr[i]] && !itemsFound[[arr[i][1], arr[i][1]]]) {
            uniques.push(arr[i]);
            itemsFound[arr[i]] = true;
            itemsFound[[arr[i][1], arr[i][0]]] = true;
        }
    }
    return uniques;
}

I hope it helps.我希望它有所帮助。

there are two parts有两部分

  1. similar should be considered应该考虑类似的
  2. among similar, one with smaller first key should stay在相似中,第一个键较小的应该保留

1. similar should be considered 1.类似应考虑

here you can just make the key for hashmap in such a way that similar items produce same key在这里,您可以为 hashmap 制作密钥,使类似的项目产生相同的密钥

one way to do that is sort the items in the tuple and then form the key, as there are two items only, first one will be min and second one will be max一种方法是对元组中的项目进行排序,然后形成键,因为只有两个项目,第一个是最小值,第二个是最大值

let a = [
  [5, 6],
  [1,1],
  [6,5],
  [1,1],
  [3,2],
  [2,3]
]

function makeUnique(arr) {
  var uniques = [];
  var itemsFound = {};
  for(var i = 0, l = arr.length; i < l; i++) {
      let [a,b] = arr[i];
      const hashKey = [ Math.min(a,b), Math.max(a,b)];
      var stringified = JSON.stringify(hashKey);
      if(itemsFound[stringified])  continue; 
      uniques.push(arr[i]);
      itemsFound[stringified] = true;
  }
  return uniques;
}

let ans1=makeUnique(a)
console.log(ans1);

2.among similar, one with smaller first key should stay 2.在同类中,第一个键较小的应该保留

now you can remember in the hashmap what the value for a key was and keep updating it based on the correct candidate现在您可以记住 hashmap 中某个键的值是什么,并根据正确的候选者不断更新它

let a = [
  [5, 6],
  [1,1],
  [6,5],
  [1,1],
  [3,2],
  [2,3]
]

function makeUniqueSmallerFirst(arr) {
  var items = {};
  for(var i = 0, l = arr.length; i < l; i++) {
      let [a,b] = arr[i];
      const hashKey = [ Math.min(a,b), Math.max(a,b)];
      var stringified = JSON.stringify(hashKey);
      
      if (stringified in items) {
          let previous = items[stringified];
          if (previous[0] > arr[i][0]) {
              items[stringified] = arr[i];
          }
      } else {
          items[stringified] =  arr[i]  // I am just storing  the array because if I see a similar item next time, I can compare if that has first item smaller or not 
      }
      
  }

  return Object.values(items); // this doesn't guarantee output order though
  // if you want order as well . you can iterate over input array once more and arrange the items in the preffered order.
}

let ans2=makeUniqueSmallerFirst(a)
console.log(ans2);

UPDATED (More simple and faster example for ES5+):已更新(ES5+ 更简单、更快速的示例):

function makeUnique(arr) {
    return new Set(a.map(
        arr => JSON.stringify(arr.sort((a, b) => a - b)))
    )
}

const m = makeUnique(a)
console.log(m) // 

OLD:老的:

This is an example of code that makes a two-dimensional array with arrays of any length unique.这是一个代码示例,它使具有任意长度的 arrays 的二维数组唯一。

let a = [
    [5, 6],
    [1, 1],
    [6, 5],
    [1, 5],
    [3, 2],
    [2, 3],
    [6, 5, 3],
    [3, 5, 6]
]

function isUnique(uniqueArray, checkedArray) {
    let checked = [...checkedArray];
    let unique = [...uniqueArray];
    let uniqueValue = 0;
    unique.forEach(value => {
        if (checked.includes(value)) {
            checked.splice(checked.indexOf(value), 1)
        } else uniqueValue++;
    })
    return uniqueValue > 0;
}

function makeUnique(array2d) {
    let unique = [array2d[0]]
    array2d.forEach(checkedArray => {
        if (unique.some(uniqueArray => {
                if (checkedArray.length !== uniqueArray.length) return false;
                return !isUnique(uniqueArray, checkedArray)
            }
        )) return 0;
        else unique.push(checkedArray)
    })
    return unique
}

console.log(makeUnique(a)) // [ [ 5, 6 ], [ 1, 1 ], [ 1, 5 ], [ 3, 2 ], [ 6, 5, 3 ] ]

isUnique() this function checks if the numbers in both arrays are unique, and if they are, it outputs true. isUnique() this function 检查两个 arrays 中的数字是否唯一,如果是,则输出 true。 We use the copy through spread operator, so that when you delete a number from an array, the array from outside is not affected.我们使用传播运算符进行复制,这样当您从数组中删除一个数字时,来自外部的数组不会受到影响。

makeUnique() function makes the array unique, in the following way: It checks if our unique two-dimensional array has at least one array that is identical to checkedArray makeUnique() function 通过以下方式使数组唯一:它检查我们的唯一二维数组是否至少有一个数组与checkedArray相同

The first check if the arrays are of different lengths - they are unique, skip and check for uniqueness, if,isUnique gives out true, then the array is skipped by return 0首先检查 arrays 是否具有不同的长度 - 它们是唯一的,跳过并检查唯一性,如果 isUnique 给出 true,则return 0跳过数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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