-5

How do I return the largest numbers from each sub array of a multidimension array? the output will be an array of largest numbers.

For example array = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]

returning value [ 5, 27, 39, 1001 ]

I tried like

function largestOfFour(arr) {

  for(var i = 0; i < arr.length; i++) {
    large = 0;
    for(var j = 0; j < arr[i].length; j++) {
      if(arr[i][j] > large) {
        large = arr[i][j];
      }
    }
  }
  return arr.push(large);
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

the output is only largest of first sub array (5)

J. Sadana
  • 11
  • 4

3 Answers3

2

I have been through the code and ended with a final solution. The first for loop iterates through the big array and the second one through the components of the subarray. The if checks for the biggest number.

function largestOfFour(arr) {
  var main = [];
  for(k=0;k<arr.length;k++){
     var long=0;
       for(i=0;i<arr[k].length;i++){
          if(long<arr[k][i]) {
              long=arr[k][i];
          }
       }
   main.push(long);
   }
  return main;
}
feralamillo
  • 819
  • 8
  • 10
1

i have got answer to my question

function largestOfFour(arr) {
  var newArr = [];
  for (i=0; i<arr.length; i++) {
    var largest = 0;
    for (j=0; j<arr[i].length; j++) {
      if (arr[i][j] > largest) {
        largest = arr[i][j];
      }
    }
    newArr.push(largest);
  }
  // You can do this!
  return newArr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
J. Sadana
  • 11
  • 4
0

If you want to use a simple loop, you need to create a return array and push the results there. In your code you have pushed an item only at the end (return arr.push(large)).

Hope it's clear

Regards,

Dan

Daniel Rosano
  • 695
  • 5
  • 16