user1488934
user1488934

Reputation: 277

Error parsing array through IF Statement

I need to loop through an entire 2D array (OldTable) to check that Column1 has a value of 1 and Col7 is not empty (null). If the above conditions are true then push the current (i) arrays of elements into newTable. My snippet of JS is as follow...

var newTable = [];  
  for (var i=1; i<OldTable.length; i++){     
    if(OldTable[i][0]==1 && OldTable[i][7]!==null){
      newTable.push(OldTable[i]);      
    }    
  }  

Seems like a fairly straight forward thing to do but currently hitting brick wall with this error...

TypeError: Cannot read property "0" from undefined. (line 80, file "Code"

I have tried to reduce the if statement to just...

if(OldTable[i][0]==1){

...but still the same error. I'm able to display the array element just fine using...

Browser.msgBox(OldTable[50][0]);

I'm fairly new to JS so could be a simple silly error someone could point out.

UPDATE: In trying to simplying naming, I've actually made it more difficult with conflicting terminology, so have going through and updated the variable names used.

Upvotes: 0

Views: 78

Answers (1)

Andrew Willems
Andrew Willems

Reputation: 12458

Your code should work if, as noted in the comment by @Massimo, you change your loop from starting at i=1 to i=0, as shown below. Also, just to whet your appetite for more modern tools within JavaScript, I also include an essentially identical solution to the problem using ES6/ES2015.

var myArray = [
  [1, 0, 0, 0, 0, 0, 0, 'foo'    ], // should pass
  [9, 1, 1, 1, 1, 1, 1, 'foo'    ], // should fail
  [1, 2, 2, 2, 2, 2, 2, 'foo'    ], // should pass
  [1, 3, 3, 3, 3, 3, 3, null     ], // should fail
  [0, 4, 4, 4, 4, 4, 4, null     ], // should fail
  [1, 5, 5, 5, 5, 5, 5, undefined], // should pass
  [1, 6, 6, 6, 6, 6, 6, 'foo'    ]  // should pass
];

function f1(array) {
  var newArray = [];
  for (var i = 0; i < array.length; i++) {
    if (array[i][0] == 1 && array[i][7] !== null) {
      newArray.push(array[i]);
    }
  }
  return newArray;
}

const f2 = array => array.filter(e => e[0] === 1 && e[7] !== null);

console.log(f1(myArray));
console.log(f2(myArray));

Upvotes: 1

Related Questions