【问题标题】:When using using reduce with ternary inside a map, I seem to have troubles在地图中使用reduce和三元时,我似乎遇到了麻烦
【发布时间】:2022-01-16 08:25:46
【问题描述】:

这是返回一个数字数组,该数组是基本数组中数组的最大值。当我使用 for 语句时,我可以让它工作。但我试图简化它,但无法弄清楚为什么它不起作用。任何帮助都会得到帮助。

    function largestOfFour(arr) {
      return arr.map((x) => x.reduce((a, c) =>  c > a ? c : a, 0));
    }

输入输出示例:

const input = [
  [1,2,3,4,5],
  [6,5,4,3,2,1],
  [1,7,3,4,5,6],
];

function findHighestElements(arr) {
    return arr.map((x) => x.reduce((a, c) =>  c > a ? c : a, 0));
}

console.log(findHighestElements(input)); // [5,6,7]

【问题讨论】:

  • 请添加输入和预期输出。
  • 什么不起作用?预期的输入和输出是什么?你会得到什么作为输出?
  • [[1, 2, 3][4, 5, 6][7, 8, 9]] -> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 你没有用逗号分隔数组

标签: javascript dictionary reduce


【解决方案1】:

你不需要减少,只需Math.max即可。像这样:

function findMaxNumbers(arr) {
  return arr.map((x) => Math.max(...x));
}

let test = [[1, 2, 3],[4, 5, 6],[7, 8, 9]];
console.log(findMaxNumbers(test));

【讨论】:

    【解决方案2】:

    如果你有小于零的值,你需要删除起始值

    x.reduce((a, c) =>  c > a ? c : a, 0)
                                       ^
    

    或使用非常小的起始值,例如-Number.MAX_VALUE

    【讨论】:

      【解决方案3】:

      要获得所有最大值中的最大值,您可以减少减少量。如果您只想要最大值,请映射减少。

      const maxOfArray = a => a.reduce((a, c) => c > a ? c : a, -Number.MAX_SAFE_INTEGER); // thanks to Nina
      const conciseVLAZMax = a => Math.max(...a); // thanks to VLAZ 
      
      let a = [
        [1, 2, 3],
        [6, -1, -2],
        [3, 4, 5],
      ]
      
      let maxs = a.map(maxOfArray);
      let maxMax = maxOfArray(maxs);
      
      console.log(maxs);
      console.log(maxMax);

      【讨论】:

      • 我只使用maxOfArray = xs => Math.max(...xs) 而不是.reduce。无需重新发明轮子。
      • 感谢 VLAZ。添加。我认为 OP 的印象是 max 函数中存在与 ternery-operator 相关的错误,因此使用 OP 代码具有解释性优势。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      相关资源
      最近更新 更多