[英]How to only allow an array to be pushed into an array once?
我有一個數組,其中有其他數組已被推入。舉個例子:
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] ];
在該陣列中可以看到,有兩個陣列具有相同的組數字1
, 2
和3
。 我想以某種方式設置條件說:
如果此數組已存在,則不要再以任何順序添加此數組以防止這種情況發生。 因此,當循環中出現這組數字再次出現時,它將跳過它。
您可以使用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)
您可以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);
接受的答案不尊重特殊情況,其中只有兩個值在數組中,並且數組必須檢查不同計數中的兩個值,如
[1, 1, 2]
和
[1, 2, 2]
這是不同的陣列。
對於工作解決方案,我建議使用Map
並計算第一個數組的相同值的出現次數,並減去另一個arrray的值的計數。
結果返回檢查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.