Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want a output of [-1,-2,-7,-3] array using javascript i have to find maximum in this


What I have tried:

var arr = [-1,-2,-3,-6,-7];
var max = 0;

for(var  i = 0; i < arr.length; i++)
    {
        
        if(arr[i] < 0 && arr[i] > max)
        {
            max = arr[i];
        }
        
    
    }
    console.log(max);
Posted
Updated 24-Oct-21 12:17pm
v2
Comments
gggustafson 24-Oct-21 15:59pm    
Your code will return 0 as the max. The maximum value in arr is -1.
Gautam Verma Oct2021 24-Oct-21 16:07pm    
yes i want to know maximum value in negative array

1 solution

You might want to think through the code, step by step.

You define max as 0 before you even get into the loop. Think about that for a few seconds. Are any of your array values ever going to be greater than 0?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900