在数组数组的map()中使用reduce()

Using reduce() within map() on array of arrays

本文关键字:数组 reduce map      更新时间:2023-09-26

我正在进行一个免费的codecamp挑战,我想知道为什么我的代码不起作用以及如何纠正它。

目标是"从每个提供的子阵列中返回一个由最大数量组成的阵列。"

我的尝试是使用reduce作为映射函数来映射输入数组:

function largestOfFour(arr) {
    arr = arr.map(function(innerArray){
       innerArray = innerArray.reduce(function(previousValue,currentValue){
           return currentValue > previousValue ? currentValue : previousValue;
       });
    });
    return arr;
}
console.log(largestOfFour([[4, 5, 1, 3],[1, 2, 3, 4]]));

当前输出为:[undefined, undefined]

我应该如何修复我的代码?

map回调中,您应该返回reduce:的结果

function largestOfFour(arr) {
  return arr.map(function(innerArray){
    return innerArray.reduce(function(previousValue,currentValue){
      return currentValue > previousValue ? currentValue : previousValue;
    });
  });
}

请注意,有一些较短的方法可以做到这一点。

有一种更简单的方法

function largestOfFour(arr) {
    return arr.map(function(innerArray) {
      return Math.max.apply(null, innerArray);
    });
}

Math.max可以用多个参数调用,就像在Math.max(3,4,5,6)中返回6一样。

使用apply,我们可以向函数传递一个参数数组,就像在.apply(thisValue, [3,4,5,6])中一样,并执行相同的操作。

由于有一个数组数组,我们可以映射外部数组,并返回Math.max.apply(thisValue, innerArray)的结果,并且由于thisValue在这里不重要,所以只通过null就可以了。

解决的另一种方法

function largestOfFour(arr) {
  return arr.map(function(innerArray) {
    // sort innerArray ascending
    return innerArray.sort(function sort(a, b) {
      return a > b;
    }).pop(); // << get the last element (the max)
  });
}
var result = largestOfFour([
  [4, 5, 1, 3],
  [1, 2, 3, 4]
]);
console.log(result);
document.write(result);