Reputation: 663
How do I remove 1 and 3 from below array in array?
[[1,2], [3,4,5]]
[[2],[4,5]]
was thinking about pop() but stuck somewhere.
Upvotes: 0
Views: 79
Reputation: 27222
Try this :
var arr = [[1,2], [3,4,5]];
for (var innerArray of arr) {
// Using array.splice()
for (var element of innerArray) {
if (element === 1 || element === 3) innerArray.splice(innerArray.indexOf(element), 1);
}
}
console.log(arr);
Upvotes: 0
Reputation: 192317
You can map the array, and got all items, but the the 1st, with Array.slice()
:
const arr = [[1,2], [3,4,5]];
const result = arr.map(item => item.slice(1));
console.log(result);
Upvotes: 0
Reputation: 1601
Try to use JavaScript built-in function shift()
.
var a = [[1,2], [3,4,5]];
a.map(item => {
item.shift();
return item;
});
console.log(a); // [[2], [4, 5]]
Official guide: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
Upvotes: 1
Reputation: 400
Loop through the main array as you normally would, like
let array = [[1,2], [3,4,5]]
for (let el of array) {
// Now you'll be accessing each array inside the main array,
// YOu can now remove the first element using .shift()
el.shift();
}
Upvotes: 0
Reputation: 25322
const a = [[1,2], [3,4,5]];
console.log(
a.map(item => item.splice(1))
)
Basically you're mapping each item of the array with the same array without the first element (since splice
mutate the array).
If you want have a copy also of the inner array, then you should use slice instead.
Upvotes: 0