簡體   English   中英

從數組數組中刪除元素

[英]Remove element from an array of arrays

我想刪除一個元素,在這種情況下是另一個數組中的數組

arr = [['a','b'],['c','d'],['e','f']];
tag = ['c','d'];

我想從 arr 中刪除標簽,為此我正在嘗試這樣做:

arr.splice(arr.indexOf(tag), 1);

但我不知道為什么它不起作用,我怎么能這樣做?

它不起作用,因為[1, 2, 3] != [1, 2, 3]在 javascript 中。 數組和對象的比較不是由值完成的。 這也適用於indexOf()

你需要告訴 javascript 你所說的平等是什么意思:

 arr = [['a','b'],['c','d'],['e','f']]; tag = ['c','d']; function array_equals(a, b){ return a.length === b.length && a.every((item,idx) => item === b[idx]) } console.log(arr.filter(item => !array_equals(item, tag)))

您需要檢查數組中的每個項目,因為使用Array#includes ,您會檢查對象引用,即使值相同,該引用也不相同。

假設檢查的數組長度相同。

 var arr = [['a', 'b'], ['c', 'd'], ['e', 'f']], tag = ['c','d'], result = arr.filter(a => !a.every((v, i) => v === tag[i])); console.log(result);

您將需要使用雙重過濾器。 第一個分隔數組,第二個將比較每個值並過濾掉標簽元素。

 arr = [['a','b'],['c','d'],['e','f']]; tag = ['c','d']; console.log(arr.filter(el=> el.filter((c,i)=> c != tag[i]).length != 0))

在更懶惰的替代方案中,如果沒有任何值包含, ,則可以將數組轉換為字符串並進行比較:

 var arr = [['a', 'b'], ['c', 'd'], ['e', 'f']], tag = ['c', 'd']; console.log( arr.filter(a => a != tag + '') )

這是一個過濾器函數,它從數字數組的數組中刪除數字 5:

 let winComb = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7], ]; for (let i = 0; i < winComb.length; i++) { for (let j = 0; j < 3; j++) { newArr = winComb[i].filter(function (item) { return item !== 5; }); } console.log(newArr); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM