0

Given the following sample:

var arr = [
  [1,2,3,4,56],
  [45,5,56,67,4],
  [5,4,5,88,75],
  [2,4,5,66,7]
];

var len = arr.length; 
for(var i = 0; i < len; i++) {
  var parent = arr[i];
  for(var j = 0; j < parent.length; j++) {
    console.log(parent[j]);
  }
}

How would I determine if the value at each index in the nested arrays are lesser/greater than the next array? I tried using parent[j][0] > parent[j][1], but that returns undefined.

2
  • What's the objective? Can't you just sort the arrays and figure out from there? Commented Jul 22, 2013 at 22:45
  • The arrays are values from a table - a 4 column multi-row table. If the value in cell 1 is greater than cell 2, add specific styling. If cell 3 is greater than 4, add styling. So on and so forth for each row. The multi-dimensional array is a representation of the table. Commented Jul 22, 2013 at 22:50

1 Answer 1

2

Try:

  var evenParent = arr[i];
  var oddParent = arr[i+1]
  for(var j = 0; j < parent.length; j++) {
    console.log(evenParent[j] + " " + oddParent[j]);
  }
  ++i;

This does test the elements in one row to the element in the same column, next row.

If you want to test the element in one column to the element in the next column, same row:

var parent = arr[i];
for (var j =0; j < parent.length; j+=2) {
    console.log(parent[j] + " " + parent[j+1]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

You would just need a check when reaching the last array if(i+1 < len)
@koala_dev True. You should test that arr[i] and arr[i+1] both exist before using them. Or you could verify that len is even before the loop. Also, it would be better to use i+=2 in the for, I suppose, rather than ++i twice.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.