簡體   English   中英

Javascript數組:刪除數組中包含在數組中的元素

[英]Javascript arrays: remove element contained in array inside array

想象一下:

const newItem = ['item 1', 'item 0', 'item 1', 'item 2', 'item 1', 'item 0'];

如果要刪除所有“項目1”,可以使用:

for (let i = newItem.length-1; i--;){
    if (newItem[i] === "item 1") newItem.splice(i, 1);
}

問題是如果我在另一個數組中有一個數組,該怎么辦?

const newItem = [
    ['item 1', 'item 0', 'item 1'],
    ['item 2', 'item 1', 'item 0']
];

謝謝!

您可以使用mapfilter map將返回一個新數組,並在回調函數中檢查['item 1', 'item 0', 'item 1']['item 2', 'item 1', 'item 0'] includes item 1

 const newItem = [ ['item 1', 'item 0', 'item 1'], ['item 2', 'item 1', 'item 0'] ]; let k = newItem.map(function(item) { return item.filter(elm => elm !== 'item 1') }); console.log(k) //newItem is not changed console.log(newItem) 

您可以結合使用mapfilter

 const newItem = [ ['item 1', 'item 0', 'item 1'], ['item 2', 'item 1', 'item 0'] ]; console.log(newItem.map(a => a.filter(e => e !== 'item 1'))); 

只需使用嵌套的forEach()循環:

 const newItem = [ ['item 1', 'item 0', 'item 1'], ['item 2', 'item 1', 'item 0'] ]; newItem.forEach((innerArray) => { innerArray.forEach((innerItem, i) => { if (innerItem === "item 1") innerArray.splice(i, 1); }); }); console.log(newItem); 

如果知道要訪問的索引,一種輕松訪問此索引的方法:

var arr = [[1,2,3], [5,6,7]];
console.log(arr[0][1]); // This will print 2, the second element of the first array item.

您還可以使用嵌套循環輕松地迭代嵌套數組項:

var arr = [
  ["item1", "item2", "item3"], ["item1", "item2", "item3"]];
arr.forEach(function(arrayItem){
    arrayItem.forEach(function(item, index, array){
         if(item === "item1"){
             array.splice(index, 1); // Removes the matching item from the arrayItem.
         }
    });
});

暫無
暫無

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

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