I have a 2D array that I am trying to manipulate/merge similar entries. I push -1 on the 3rd index of the arrays I am marking for delete. Here is a sample of rowArray:
[
[44,16,0,-1],
[44,16,1,-1],
[44,16,0]
]
In my for-loop, I decrement through the array and if rowArray[i][3] exists I am trying to pop this array from the matrix. My problem is that in my if i'm always receiving a problem. When I use:
if( rowArray[i][3] ).. or if( rowArray[i][3] !== 'undefined').. etc. then I receive a TypeError:
Uncaught TypeError: Cannot read property 'length' of undefined
I have also tried using:
if( rowArray[i].length > 3 ) but this gives me the error:
Uncaught TypeError: Cannot read property 'length' of undefined
Here is my code:
rowArray = [ [44, 16, 0, -1], [44, 16, 1, -1], [44, 16, 0] ];
for (var i = 1; i < rowArray.length; i++) {
if (rowArray[parseInt(i - 1)][0] == rowArray[i][0] && rowArray[parseInt(i - 1)][1] == rowArray[i][1]) {
rowArray[i][2] += parseFloat(rowArray[parseInt(i - 1)][2]);
rowArray[parseInt(i - 1)][3] = -1;
}
}
for (var i = rowArray.length; i >= 0; i--) {
console.log(rowArray[i].length);
if (rowArray[i][3] !== 'undefined') {
rowArray.splice(i, 1);
}
}
Expected Output:
[[44,16,1]]
I should mention that I am using jQuery 3.4.0. Also open to better solutions to this problem (as always).
parseInt(i - 1). It's already an integer.