1

I've been trying to fill up a 2D array with JavaScript and I keep crashing my browser so I assume I have infinite recursion but I can't seem to find my error. Here's my code:

//The two sequences to compare
var sequence1 = "ATTGCTGACTTCA"
var sequence2 = "ATGCTACTA"
  //Creates multi-dimensional array dependent on sequence lengths
var arr = new Array(sequence1.length + 1)
for (i = 0; i < sequence1.length + 1; i++) {
  arr[i] = new Array(sequence2.length + 1);
}
//Fills array with 0s
for (i = 0; i < arr.length; i++) {
  var col = i;
  for (i = 0; i < arr[col].length; i++) {
    arr[col][i] = 0;
  }
}
0

2 Answers 2

2

When you filling your array, you change the value of i by inner loop, and did not change it back to it's original value after the inner loop! Dont use the same variable name in outer and inner loops!

for (i = 0; i < arr.length; i++) {
  var col = i;
  for (i = 0; i < arr[col].length; i++) {
    arr[col][i] = 0;
  }
  i = col;
}

what you realy should do:

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

Comments

1

You can use Array#from, Array#map and Array#fill.

var arr = Array.from({
    length: sequence1.length + 1
}).map(() => Array.from({
    length: sequence2.length + 1
}).fill(0));

var sequence1 = "ATTGCTGACTTCA",
    sequence2 = "ATGCTACTA";

//Creates multi-dimensional array dependent on sequence lengths
var arr = Array.from({
    length: sequence1.length + 1
}).map(() => Array.from({
    length: sequence2.length + 1
}).fill(0));

console.log(arr);

Explanation:

var arr = Array.from({
    length: sequence1.length + 1
})
// Create an array of passed `length` of `undefined` elements

// map will iterate over all the elements of the array and update the value of each element
// Create new array and use this as the individual item in the main array
.map(() => Array.from({
    length: sequence2.length + 1
}).fill(0));

2 Comments

The outer array will be filled with the sequence1.length + 1 references to the same nested array. Check the arr[0][0] = 42; console.log(arr[1][0]);
@zerkms Thanks for pointing. I forgot about array references. Used map now. :)

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.