Your code will throw an error thisArray is undefined
because
- Inside variable
k
loop, you have removed the item ondata[j]
variable if it matches the condition. So the length ofdata[j]
will be decreased once you remove the item fromdata[j]
. - And you have looped k from
0 ~ 3
, so if one item is removed fromdata[j]
, its’ length will be 3 (it meansdata[j][2]
will be undefined.)
So you will get that error. It is needed to include the handler for undefined
error part as follows.
const data = [
[
[0,0,4],
[0,1,4],
[0,0,4],
[0,0,4]
],
[
[0,1,4],
[0,1,4],
[0,0,4],
[0,1,4]
],
[
[0,0,4],
[0,0,4],
[0,1,4],
[0,1,4]
]
];
for (var j = 0; j < 3; j++) {
for (var k = 0; k < 4; k++) {
var thisArray = data[j][k];
if (thisArray && thisArray[1] == 0) {
data[j].splice(k,1);
k --;
}
}
}
console.log(data);
Or simply, it can be done using Array.map
and Array.filter
.
const data = [
[
[0,0,4],
[0,1,4],
[0,0,4],
[0,0,4]
],
[
[0,1,4],
[0,1,4],
[0,0,4],
[0,1,4]
],
[
[0,0,4],
[0,0,4],
[0,1,4],
[0,1,4]
]
];
const output = data.map((item) => item.filter(subItem => subItem[1]));
console.log(output);
CLICK HERE to find out more related problems solutions.