0

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

4
  • You don't need to use parseInt(i - 1). It's already an integer. Commented Jun 24, 2019 at 20:15
  • please share your expected output Commented Jun 24, 2019 at 20:16
  • @Barmar I forgot to take that out from before, used it to be certain it wasn't making any problems. Commented Jun 24, 2019 at 20:17
  • 1
    Why do you need to mention the jQuery version? There's no jQuery calls anywhere in the code you posted. Commented Jun 24, 2019 at 20:17

1 Answer 1

3

The problem is that in the second loop you are starting from the rowArray.length which is not right because the last item is rowArray.length-1. That's because the array starts from 0. So your second loop would be like this:

for (var i = rowArray.length-1; i >= 0; i--) {
   console.log(rowArray[i].length);
   if (rowArray[i][3] !== 'undefined') {
     rowArray.splice(i, 1);
   }
 }
Sign up to request clarification or add additional context in comments.

3 Comments

for (let i = rowArray.length; i--;) ... i>=0 is pointless because 0 is already falsy. i-- returns i before it was changed. might as well just combine them.
@Iwrestledabearonce.you are just right but to bold the main problem and don't change anything else to show the solution I didn't want to change it more. Thanks for the mentioning.
you changed as much or more in your version than i did in mine. i only removed a few things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.