@bahramb92 I approached this problem in the same way as you and had exactly the same problem.
This issue here is your line
var number = 0;
By setting the variable to 0, in a subarray of negative number it will always see that 0 is bigger and push this into your array.
What you need to do is find a way of resetting this variable to one of the array values instead of a fixed value. That way you are always comparing two values within the array against each other to find the highest, which removes the possibility of returning a value that isnât in the array.
My working code is:
function largestOfFour(arr) {
// You can do this!
let numbersArr = [];
for (let i = 0; i < arr.length; i++) {
let highestNumber = arr[i][0];
for (let j = 0; j < arr[i].length; j++) {
if (arr[i][j] > highestNumber) {
highestNumber = arr[i][j];
}
}
numbersArr.push(highestNumber);
}
console.log(numbersArr);
return numbersArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
function largestOfFour(arr) {
// You can do this!
let result = [];
for (let el of arr) {
result.push(el.reduce((acc,cur) => Math.max(acc,cur)));
}
return result;
}
Math.max doesnât take an array, so to pass an array to it, you need to spread it into separate arguments, which is whatâs being done here, takes the array and passes the elements in it to the function.