Return Largest Numbers in Arrays ( doesn't work with -3)

Return Largest Numbers in Arrays

Guys, my code works only with some test cases. I have problems with the last one. Can anyone explain to me why I get [ 25, 48, 21, -10 ] instead of [25, 48, 21, -3] in the last example?

   const largestOfFour = (arr) => {
    let new_arr = [];
    for (let i = 0; i < arr.length; i++) {
        let max = arr[i][0];
        for (let j = 0; j < arr[i].length; j++) {
            if (arr[i][j] > max && arr[i][j] > 0 || arr[i][j] < 0) {
                max = arr[i][j];
            }
        }
        new_arr.push(max);
    }
    return new_arr;
};
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])); //[5, 27, 39, 1001]
console.log(largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])); //[27, 5, 39, 1001]
console.log(largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])); //[25, 48, 21, -3]

Challenge: Return Largest Numbers in Arrays

Link to the challenge:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

HI @heroisaprinciple !

Welcome to the forum!

I would take a close look at your if statement here

Since all of the numbers in the last sub array are negative then this would never be true right?

So this would always get executed instead

which means the current element would replace max each time here

Since -10 is the last element in that sub array, then -10 is assigned to max and therefore pushed to the new_arr

Also, I missed this part earlier.

I think you meant to write arr[i][0]

Okay. I missed let max = arr[i][0];
Thank you for noticing it.
But I still don’t get how to make -3 appear in the array…

You’re close but there are two places you need to look at.

No.1:
You created this max variable and are assigning the first number of each sub array.

For this inner j loop, you shouldn’t start counting at 0.
There is no point in comparing the first element of the sub array to itself, right?
You should change this part

to start counting at the second number in the array and then you increment from there.

No.2:
For the if statement, you want to say if the current element is greater than max then you can assign it to the max variable.

I am not sure what the rest of this stuff is supposed to do

Hopefully that helps!

1 Like

Thank you! I haven’t noticed how inattentive I am. You are amazing!

1 Like

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