[英]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: 如果要删除所有“项目1”,可以使用:
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
和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
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)
You can use a combination of map
and filter
: 您可以结合使用
map
和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: 只需使用嵌套的
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);
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.
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.