Return Largest Numbers in Arrays, where i lag?

Return Largest Numbers in Arrays, where i lag?
0

#1

Tell us what’s happening:

Your code so far

function largestOfFour(arr) {
  // You can do this!
  large = [];
  for(i=0;i<arr.length;i++)
    {
      for(j=0;j<arr;j++)
        {
      large = Math.max.apply(Math, arr);
        }
     }
      return large; 
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/60.0.3112.113 Chrome/60.0.3112.113 Safari/537.36.

Link to the challenge:


#2

if you want to use Math.max.apply, you don’t need second for repetition. Math.max.apply already check each second level array element for you. Your code will be like this :

function largestOfFour(arr) {
  // You can do this!
  large = [];
  for(i=0;i<arr.length;i++)
    {
      large = Math.max.apply(Math, arr);
    }
      return large; 
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

After remove for repetition, look at this :

      large = Math.max.apply(Math, arr);

you mention arr. You won’t get any result because your program expect list of number but you give them list of array. To solve this, set your program to look at each subarray that contain number

      large = Math.max.apply(Math, arr[i]);

Is it done ? not yet. This is your output so far :

  [1001]

this is the requested output :

 [5, 27, 39, 1001]

Why it happen ? In your program, instead of save every largest value, you replace it. You need to use push() to save every new largest value

    large.push(Math.max.apply(Math, arr[i]));

this is your final code :

function largestOfFour(arr) {
  // You can do this!
  large = [];
  for(i=0;i<arr.length;i++)
    {

      //large = Math.max.apply(Math, arr[i]);
      large.push(Math.max.apply(Math, arr[i]));
     }
      return large; 
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

I know it’s pretty confusing, Just mention if you need further explanation


#3

@alta9

Thank you bro, First of all its not confusing , its looking easy for me from past two or three challenges.

I just tried the way early as you mentioned but I stopped with a single value.

So I made a second loop J inside the loop I.

And yes you are right, i forgot to push those values as newbie i cant make a good thinking of syntax & function when and where to use

thanks a lot @alta9