Return Largest Numbers in Arrays don't understand

Tell us what’s happening:
I don’t understand why the variable temp incorrectly assigned. Why variable temp return all elements in subarray? it must return only max element in subarray…
Your code so far


const largestOfFour = arr => {
  // You can do this!
  return arr.map(item => item.filter(e => {
    let temp = 0
    if (temp < e) temp = e
    //return temp
  }))
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays

Aside from the use of temp, there are bigger problems lying around that is your approach can’t find the largest number of any array.

Notice how your temp resets to 0 every time an element is visited. This means temp is always 0. So, you can’t make a proper comparison. For example, if you have an array [1, 2, 3]
On each visit, temp = 0 and you end up doing 0 < 1 , 0 < 2, 0 < 3.

Suppose you’ve pulled out temp to the outer scope like this.

function(arr) {
    let temp = 0

    return arr.map(...
}

Now, temp is tracking the largest number across every array, unless you reset temp for each array.
This isn’t what the exercise is asking for. So, you can quickly see how your approach complicates the problem.

It’s upto you whether you want to proceed your way or find a better way, but consider this.

arrays.map( arr => max(arr) )

Will it solve the problem and is it simpler?

1 Like

I would nest another function within the loop, checking the inside of the sub arrays to find the largest of each sub array. Then assign temp to the result of that function. I haven`t gotten here in the curriculum, but have definitely done this type of thing in C++, so I would guess that the logic would carry over.

Thank you very much, I seem to understand.

No, I do not want to look for easy ways to solve the problem. The more difficult the better.

Well, if that’s what you want, I can’t hold you back, but just know that there is a difference between solving easy problems and solving easy problems in a difficult way…

1 Like

A situation may arise that you will get such a difficult task, the solution of which will not be on the Internet. And how will you solve it if you are constantly looking for easy ways? Therefore, I better solve this problem in ten different ways, but I will perfectly understand how it works.

At this point you’re practically telling them how to solve the problem, don’t you think? I’m just pointing that out.

I guess I went beyond just answering OP’s question; yeah, it seems I was telling how to solve the problem and went overboard.