I am working on a coding challenge to take a given array which consists of sub-arrays, search for the largest number in each sub-array, and finally return a new array consisting only of the largest numbers. My thought process was to create variables out of each subarray, write a for-loop comparing each value within the array, then push the largest value to a new array. After writing my first for-loop I tested my code and see that I am getting an unexpected result of the entire first subarray being pushed into my new array. I am looking for the mistake before I write the next three loops. Thank you. Edit: This is for beginner JavaScript coders and the suggestion indicates to use comparison operators in your solution.
function largestOfFour(arr) {
var one = arr[0];
var two = arr[1];
var three = arr[2];
var four = arr[3];
var newArr = [];
for (var i = 0; i < one.length; i++){
var oneLrg = 0;
if (one[i] > oneLrg){
oneLrg = one[i];
}
newArr.push(oneLrg);
}
return arr;
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])); //This test case returns [4,5,1,3] instead of just [5]
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…