简体   繁体   English

如何只允许将数组推入数组一次?

[英]How to only allow an array to be pushed into an array once?

I have an array that has other arrays in it which have been pushed in. For an example: 我有一个数组,其中有其他数组已被推入。举个例子:

const Arrays = [ [1,2,3], [4,5,6], [7,8,9], [2,1,3] ];
let myArr = [];

Arrays.map(arr => {
  if(myArr.indexOf(arr)){
   return
  }
  myArr.push(arr)
})

const myArr = [ [1,2,3], [4,5,6], [7,8,9], [2,1,3] ];

In this array you can see that there are two arrays with the same set of numbers 1 , 2 and 3 . 在该阵列中可以看到,有两个阵列具有相同的组数字123 I want to somehow set a condition saying: 我想以某种方式设置条件说:

If this array already exist then do not add this array in any order again to prevent this from happening. 如果此数组已存在,则不要再以任何顺序添加此数组以防止这种情况发生。 So that when it comes in the loop that this set of numbers comes up again it will just skip over it. 因此,当循环中出现这组数字再次出现时,它将跳过它。

You can use some() and every() methods to check if same array already exists before push() . 您可以使用some()every()方法检查push()之前是否已存在相同的数组。

 const myArr = [ [1,2,3], [4,5,6], [7,8,9] ]; let input = [2,1,3] function check(oldArr, newArr) { return oldArr.some(a => { return a.length == newArr.length && a.every(e => newArr.includes(e)) }) } if(!check(myArr, input)) myArr.push(input) console.log(myArr) 

You can make temp array with sorted element with joined and check by indexOf 您可以sorted element with joined创建临时数组,并通过indexOf检查

 const myArr = [ [1,2,3], [4,5,6], [7,8,9], [2,1,3],[6,5,4] ]; var newArr = []; var temp = []; for(let i in myArr){ let t = myArr[i].sort().join(","); if(temp.indexOf(t) == -1){ temp.push(t); newArr.push(myArr[i]); } } console.log(newArr); 

The accepted answer does not respect the special case where only two values are in the array and the array has to check against two values in a different count like 接受的答案不尊重特殊情况,其中只有两个值在数组中,并且数组必须检查不同计数中的两个值,如

[1, 1, 2]

and

[1, 2, 2]

which are different arrays. 这是不同的阵列。

For a working solution, I suggest to use a Map and count the occurences of same values of the first array and subtract the count of the values for the other arrray. 对于工作解决方案,我建议使用Map并计算第一个数组的相同值的出现次数,并减去另一个arrray的值的计数。

As result return the check if all elements of the Map are zero. 结果返回检查Map的所有元素是否为零。

 function compare(a, b) { var map = new Map; a.forEach(v => map.set(v, (map.get(v) || 0) + 1)); b.forEach(v => map.set(v, (map.get(v) || 0) - 1)); return [...map.values()].every(v => !v); } var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [2, 1, 3], [1, 1, 2], [1, 2, 2], [2, 1, 1], [2, 1, 2]], unique = array.reduce((r, a) => (r.some(b => compare(a, b)) || r.push(a), r), []); console.log(unique); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

一种方法是使用.sort()以数字方式对它们进行排序,然后比较它们。

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

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