在本文中,我将解释如何解决Free Code Camp的“在数组中返回最大数”挑战。这涉及从每个子数组返回具有最大数目的数组。
我将介绍三种方法:
- 带FOR循环
- 使用reduce()方法
- 使用Math.max()
算法挑战
- 从每个提供的子数组中返回一个包含最大数目的数组。为简单起见,提供的数组将仅包含4个子数组。
- 你可以使用简单的for循环遍历数组,并使用数组语法arr
[i]访问每个成员。
function largestOfFour(arr) {
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
提供测试用例
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].
方法1:使用For循环返回数组中的最大数字
这是我的解决方案,带有嵌入的注释可以帮助您理解它
function largestOfFour(arr) {
// Step 1. Create an array that will host the result of the 4 sub-arrays
var largestNumber = [0,0,0,0];
// Step 2. Create the first FOR loop that will iterate through the arrays
for(var arrayIndex = 0; arrayIndex < arr.length; arrayIndex++) {
/* The starting point, index 0, corresponds to the first array */
// Step 3. Create the second FOR loop that will iterate through the sub-arrays
for(var subArrayIndex = 0; subArrayIndex < arr[arrayIndex].length; subArrayIndex++) {
/* The starting point, index 0, corresponds to the first sub-array */
if(arr[arrayIndex][subArrayIndex] > largestNumber[arrayIndex]) {
largestNumber[arrayIndex] = arr[arrayIndex][subArrayIndex];
/* FOR loop cycles
arrayIndex => i
subArrayIndex => j
Iteration in the first array
For each iteration: arr[i][j] largestNumber[i] if arr[i][j] > largestNumber[i]? then largestNumber[i] = arr[i][j]
First iteration: arr[0][0] => 4 largestNumber[0] => 0 4 > 0? => TRUE then largestNumber[0] = 4
Second iteration: arr[0][1] => 5 largestNumber[0] => 4 5 > 4? => TRUE then largestNumber[0] = 5
Third iteration: arr[0][2] => 1 largestNumber[0] => 5 1 > 5? => FALSE then largestNumber