user2173977
user2173977

Reputation: 1

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!

Upvotes: 0

Views: 67

Answers (4)

Dblaze47
Dblaze47

Reputation: 868

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

Upvotes: 1

brk
brk

Reputation: 50291

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)

Upvotes: 3

f-CJ
f-CJ

Reputation: 4481

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

Upvotes: 2

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

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

Upvotes: 1

Related Questions