Store a multidimensional array in a variable without knowing how many rows it will get (Javascript)

0

reviewing one of the freecodecamp algorithms in which we work with javascript I have the following code:

function largestOfFour(arr) {

var largestNumber = [0,0,0,0];

for(var arrayIndex = 0; arrayIndex < arr.length; arrayIndex++) {

for(var subArrayIndex = 0; subArrayIndex < arr[arrayIndex].length; subArrayIndex++) {

if(arr[arrayIndex][subArrayIndex] > largestNumber[arrayIndex]) { 

      largestNumber[arrayIndex] = arr[arrayIndex][subArrayIndex];
    }
  }
}
return largestNumber;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

How can I declare "largestNumber" as a multidimensional array without knowing how many rows I will get?.

    
asked by syonrod 07.11.2017 в 11:47
source

2 answers

1

Actually largestNumber is not a multidimensional array, it is an array of a single dimension whose length depends on the length of the array passed to the function.

You can declare the array without having to initially set its size.

Look at the example I give you with a small modification to keep in mind that the value in the array largestNumber may not be initialized.

I also give you a simpler function that gets the same result using the map and sort methods.

function largestOfFour(arr) {

  var largestNumber = [];

  for(var arrayIndex = 0; arrayIndex < arr.length; arrayIndex++) {

    for(var subArrayIndex = 0; subArrayIndex < arr[arrayIndex].length; subArrayIndex++) {

      if(arr[arrayIndex][subArrayIndex] > (largestNumber[arrayIndex] || 0)) { 
        largestNumber[arrayIndex] = arr[arrayIndex][subArrayIndex];
      }
    }
  }
  return largestNumber;
}

function largest2(arr){
  return arr.map(a => a.sort((x,y) => x<y)[0]);
}

var data = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
var result = largestOfFour(data);
console.log(result);
result= largest2(data);
console.log(result);
    
answered by 07.11.2017 / 12:04
source
0

This creates a multidimensional array without specifying the length of it:

var largestNumber= new Array(0,0,0,0);
    
answered by 07.11.2017 в 11:51