Naveen Dinushka

Posted on

# Return Largest Numbers in Arrays (freecodecamp notes)

In this question we are asked to Return Largest Numbers in Arrays.

Tests that we should pass

``````largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return an array.
largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27, 5, 39, 1001].
largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) should return [9, 35, 97, 1000000].
largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]) should return [25, 48, 21, -3].
``````

``````function largestOfFour(arr) {

let maxInSubArr=0
let newArr=[]

for(let i=0;i<arr.length;i++){
for (let j=0;j<arr[i].length;j++){

if(maxInSubArr<arr[i][j]){
maxInSubArr=arr[i][j]

}
}
newArr.push(maxInSubArr)
maxInSubArr=0

}

return newArr;
}
``````

``````function largestOfFour(arr) {

let newArr=[]

for(let i=0;i<arr.length;i++){

let maxInSubArr = arr[i][0];

for (let j=0;j<arr[i].length;j++){

if(maxInSubArr<arr[i][j]){
maxInSubArr=arr[i][j]

}
}
newArr.push(maxInSubArr)

}

return newArr;
}
``````

Correct Answer is Answer 2, reason being, in the first answer we do not handle negative numbers, we set it to zero initially then reset it to zero once its pushed to return array, however in the second solution we are setting it to the first item in subarray

``````myArray.map(subArr => subArr.sort((a, b) => b - a).at(0));