简体   繁体   中英

Javascript arrays: remove element contained in array inside array

Imagine something like:

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

If I want to remove all 'item 1' I can use:

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

The question is if I have an array inside another array how can I do?

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

Thanks!

You can use map and filter . map will return a new array and inside the callback check if the item which is ['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) 

You can use a combination of map and filter :

 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'))); 

Just use nested forEach() loop:

 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); 

If you know which index you want to access, one way to easily access this:

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.

You can also easily iterate the nested array items using nested loop:

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.
         }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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