javascript - 返回最大的数组

标签 javascript arrays

我一直在尝试解决这个练习问题:

Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.

但是我的代码只返回整个数组中的单个元素,如果我unshift所有最大元素,它会产生完全错误的结果,我尝试单独执行嵌套循环,它工作得很好,但是与外循环结合时会产生问题。

function largestOfFour(arr)
{
    // You can do this!
    var max = 0;
    var largestArray =[];
    for (var i = 0; i <4; i++)
    {
        for (var j = 0; j <4; j++)
        {
            if (arr[i][j]>max)
            {
              max=arr[i][j];
              largestArray.unshift(max);
              //console.log(max);
            }

        }
    }
      console.log(largestArray);
    return max;
}

largestOfFour([[4, 5, 1, 13], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

最佳答案

如何修复代码(请参阅代码中的注释):

function largestOf(arr) {
  var max;
  var largestArray = [];

  for (var i = 0; i < arr.length; i++) { // the arr length is the number of sub arrays
    max = -Infinity; // max should be reinitialized to the lowest number on each loop
    for (var j = 0; j < arr[i].length; j++) { // the length is the number of items in the sub array
      if (arr[i][j] > max) { // just update max to a higher number
        max = arr[i][j];
      }
    }
    
    largestArray.push(max); // push max after the internal loop is done, and max is known
  }

  return largestArray; // return the largest array
}

var result = largestOf([[4, 5, 1, 13], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

console.log(result);

另一个解决方案是使用Array#map ,然后申请Math#max到每个子数组以获得其最大值:

function largestOf(arr) {
  return arr.map(function(s) {
    return Math.max.apply(Math, s);
  });
}

var result = largestOf([[4, 5, 1, 13], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

console.log(result);

关于javascript - 返回最大的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46522359/

相关文章:

javascript - 悬停时不在屏幕上显示 id

javascript - 将 div 的子级插入 javascript 数组

c - 将表指针从 C 传递到汇编函数

javascript - 检测直写 Chrome ?

javascript - 使用 VueJS 根据复选框值切换输入元素的禁用属性

arrays - 如何根据键的值对 TCL 数组进行排序?

arrays - 如何使用 qsort 对结构体指针数组进行排序

python - 如何将 4 位数据加载到 numpy 数组中

javascript - 关于防止通过 MAC 触摸栏输入字母的 oninput 事件?

cocoa - 使用 xCode 制作图表