Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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)

share|improve this question
    
10  
I am tempted to write array.map(Math.max.apply.bind(Math.max, null)) as answer. – thefourtheye Aug 11 '15 at 7:58
    
@thefourtheye it works perfectly! Put it as answer, I upvote you: jsfiddle.net/3qf9qxu2 – Marcos Pérez Gude Aug 11 '15 at 8:00
3  
@thefourtheye: That's just awful. Beautiful. Awful. Beautiful. Aaaaah! – T.J. Crowder Aug 11 '15 at 8:00
1  
@T.J.Crowder I know :D If OP had made some effort I would have added that also in the answer and explained it :( – thefourtheye Aug 11 '15 at 8:02

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;
}
share|improve this answer

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

share|improve this answer

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]]);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.