Find the biggest number in an array challenge

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

I have done this challenge and came up with a way that it does return you a new array consists of all the biggest numbers from the sub-arrays.

But only when the numbers in it are bigger than 0.

function a(arr){
  let result=[];
  for(let i = 0;i<arr.length;i++){
    let sub_arr = arr[i];
    
    let biggest_sub=0;
    for(let j=0;j<sub_arr.length;j++){
      
      if(sub_arr[j]>biggest_sub){
        biggest_sub=sub_arr[j];
      }
    }
    result.push(biggest_sub);
  }
return result;
}

console.log(a([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]));

how should I mod it so that negative numbers will be compared too?

You can simply call Math.max() function on your array. Make sure you use spread operator because it just takes series of numbers delimited by commas.

1 Like

I will give it a try later. Thanks!

Hi,

A work around for this can be done declaring biggest_sub always to be the first position of the array, that way, if the array contains only negative values, it will compare the values to themselves, be aware that you’ll need to create an exception for when the array is empty.

1 Like
function a(arr){
  let result=[];
  for(let i = 0;i<arr.length;i++){
    let sub_arr = arr[i];
    

    if(sub_arr!==[]){
      let biggest_sub=sub_arr[0];
      for(let j=0;j<sub_arr.length;j++){
      
        if(sub_arr[j]>biggest_sub){
          biggest_sub=sub_arr[j];
        }
      }
      result.push(biggest_sub);
    }
    else{return "Empty array detected.";}
}
return result;
}

console.log(a([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]));

is this correct?

instead of iterating over each subArr with a for loop look at using the .sort() array method. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
this way you won’t have to initialize a biggestNumberInSubArr

so since it is always gonna be true. it is un-necessary?

@camperextraordinaire

to further the point you cant compare arrays or objects because they pass reference and not value so will always be different

i think you are looking for if(sub_arr.length > 0) {...}

1 Like

:smile: thanks for the tip.