Basic Algorithm Scripting - Return Largest Numbers in Arrays

Tell us what’s happening:
It returns 0 when the value in the sub index is < 0. Tried using else if to insert a condition for that but it messes up the whole code.

  **Your code so far**
function largestOfFour(arr) {
let large = [0,0,0,0]
for(let i = 0; i < arr.length; i++) {
    for(var j = 0; j < arr[i].length; j++) {
        if(arr[i][j] > large[i]) {
            large[i] = arr[i][j]

return large;

console.log(largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]));
  **Your browser information:**

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

Challenge: Basic Algorithm Scripting - Return Largest Numbers in Arrays

Link to the challenge:

Why start with zeros? Why not start with the first value in each subarray.

It’ll return zero because the base case, the number it is in the array large when you initialise it is a zero.

In your conditional statement you’re checking to see if are[I][j] is greater than what is already in large
So, the code is testing each element in this array [-72, -3, -17, -10] to see if it is greater than zero and if it is it is returning the number. Otherwise it keeps the original 0 in your large array.
As the numbers are minus it keeps the 0 as the conditionals statement each case if false.

To get round this you could do something like:
Set large to an empty array.
Create a variable e.g. biggestNum in the first [i] loop with the initial value of the individual arrays e.g. arr[I][0]
Then in the second loop you compare each value to that variable and if they are bigger than biggestNum
If so biggestNum is replaced with a new value i.e. the new element.
Else nothing bigger is found and biggestNum is the biggest number.
Then when each round of the second (j) loop is completed you push the biggest num to large
I hope that’s all clear. I tried to share a solution with a walk through but it’s automatically removed but the mod.

Good coding!

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.