You compare negative numbers against 0, and 0 is bigger than any negative number (the last subarray has all negatives, and largestNumber[3] is initialized with 0).
Nevermind I figured it out, someone else pointed out the same issue on the blog post:
So you can fix the negative value compare by “initializing your comparisons to the first element in the array”, like so:
var biggestNumber = [arr[0][0], arr[1][0], arr[2][0], arr[3][0]];
You can fix the negative value compare by “initializing your comparisons to the first element in the array”, like so:
var largestNumber = [arr[0][0], arr[1][0], arr[2][0], arr[3][0]];
This solution you posted passes the test, but requires that you know the size of the sub-arrays beforehand so that you can initialize every index. A more programmatic solution would be
function largestOfFour(arr) {
var biggestNumber = []; // no need to pre-initialize
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
// if index === 0, it's automatically the highest
if (j === 0) biggestNumber[i] = arr[i][j]
// otherwise return the greater value, negatives included
else biggestNumber[i] = Math.max(biggestNumber[i], arr[i][j])
}
}
return biggestNumber;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
The solution to this is quite simple. if you sort each array from lowest to highest(store the sorted array in a new array “newArr” ), the last number will always be the greatest, or sort from highest to lowest and the first number will always be the greatest. Here is my code.
ASCENDING ORDER
function largestOfFour(arr) {
let newArr = [];
let highest = [];
//sort array
for(let i = 0; i < arr.length; i++){
arr[i].sort(function(a, b){
return a - b;
});
newArr.push(arr[i]);
}//end of for loop for sorting array
//pick the last number from each array
for( let j = 0; j < newArr.length; j++){
highest.push(newArr[j][newArr[j].length-1]);
}
return highest;
}
OR
DESCENDING ORDER
function largestOfFour(arr) {
let newArr = [];
let highest = [];
//sort array
for(let i = 0; i < arr.length; i++){
arr[i].sort(function(a, b){
return b - a;
});
newArr.push(arr[i]);
}
//end of for loop for sorting array
//pick the first number from each array
for( let j = 0; j < newArr.length; j++){
highest.push(newArr[j][0]);
}
return highest;
}