- Let's return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
- Remember, you can iterate through an array with a simple for loop, and access each member with array syntax
arr[i]
.
function largestOfFour(arr) {
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
*Hints:
-You will get an array that contains sub arrays of numbers and you need to return an array with the largest number from each of the sub arrays. You will need to keep track of the array with the answer and the largest number of each sub-array.
-You can work with multidimensional arrays by Array[Index][SubIndex]
-Pay close attention to the timing of the storing of variables when working with loops
- Answer:
function largestOfFour(arr) {
let largestArr = [];
for (let i = 0; i < arr.length; i ++) {
let tempLarge = arr[i][0];
for (let j = 0; j < arr[i].length; j++) {
let num = arr[i][j];
if (num >= tempLarge) {
tempLarge = num
}
}
largestArr.push(tempLarge)
}
return largestArr;
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])); // will display [5, 27, 39, 1001]
Top comments (1)
Thank you, friend. That helped me a lot.