JavaScript 中是否有一种有效的算法可以在较大的数组集中查找不同数组的数量?

Cal*_*Oki 3 javascript arrays algorithm

给定以下数组

let array = [[1, 2], [1, 2], [3, 4], [5, 6], [2, 1]]
Run Code Online (Sandbox Code Playgroud)

I want to return the number of distinct arrays in this set. So the example above should return 3. How do I achieve this? I tried the code below, but it does not give the right answer

let distinct = 0
for (let i = 0; i < array.length; i++) {

  for (let j = i + 1; j < array.length - i; j++) {
    let difference = ingredients[i].filter(x => !array[j].includes(x))
     if (difference.length > 0) {
       distinct += 1;   
     } 
   }
 }

 return distinct;
Run Code Online (Sandbox Code Playgroud)

Ori*_*ori 10

If the order inside a sub item matters

Use Array.map() to convert each sub-array into a string (I've used String() as suggested by @trincot), create a Set from the array to remove duplicates, and get the size of the Set:

const array = [[1, 2], [1, 2], [3, 4], [5, 6]]

const distinct = new Set(array.map(String))

console.log(distinct.size)
Run Code Online (Sandbox Code Playgroud)

If the order doesn't matter

Sort each sub item, and then convert to string:

const array = [[2, 1], [1, 2], [3, 4], [5, 6]]

const distinct = new Set(array.map(o => String(o.sort())))

console.log(distinct.size)
Run Code Online (Sandbox Code Playgroud)

  • 如果保证输入由没有分隔符的内容组成,您甚至可以只使用“map(String)”。这将在内部进行“连接”,因此至少同样高效。 (3认同)