Return Largest Numbers in Arrays, stuck please help

Return Largest Numbers in Arrays, stuck please help
0.0 0

#1

Tell us what’s happening:
I am stuck with Return Largest Numbers of Arrays quiz. Please help me what I should do. Thank you!

Your code so far

function largestOfFour(arr) {
  // You can do this!
  var result = [];
  
  for (var i = 0; i < arr.length; i++) {
    for (var l = 0; i < arr[i].length; i++) {
    //var array = arr[i][l];
      result.push(arr[i][l].reduce(function(a,b) {
        return Math.max(a, b);

      }));


    } 
  }


  return result;
}

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 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36.

Link to the challenge:


#2

To solve this, I create a second array and then used some logic to determine which numbers would go into that array. Here’s a prototype to see if you can figure it out:

var newArray = new Array[];

for each of the first-level arrays {
for each of the second-level arrays {
if the second number is greater than the first number in the second-level array, put it in the newArray


#3

This is not how you declare an array in JavaScript.

Use:

var newArray = [];

#4

It’s a prototype. I’m trying to not give him real code.


#5

@krittiyaclark The problem with your solution is you are trying to use the reduce function on something that is not an array. In the inner for loop, arr[i][l] is a number (i.e. 4). What is your reasoning for wanting to use the reduce function here? Your two for loops are already iterating over every element of the two-dimensional array.


#6

You mean psedo-code?


#7

That sounds much better. Thank you.


#8

I thought that was what you meant, but wanted to clarify it for the OP.


#9

What is the best method for a second for loop?


#10

Instead of me just giving you the code to use, can you explain the algorithm you are trying to use and then I can give you hints on how to actual write the code to implement the algorithm?


#11

@randelldawson I try to use nested for loop then sort it with like .sort(function(a,b){ b - a });. Make sense?


#12

When you describe an algorithm, you should describe all the steps related to solving the challenge. When you say “I try to use nested for loop then sort it with like .sort(function(a,b){ b - a });”, then you need to tell us what “it” is. What are you trying to sort and why are you sorting it? After sorting “it”, what are you hoping to gain.

Be as specific as possible when describing why you are doing instead of what you are doing. I can see what you are doing by looking at the code, but I need to understand why you are approaching the problem a certain way, to better guide you to a solution of your own understanding.


#13

I passed it by using comparison operators. It was a hard one. Thank you for your help.