在地图中使用 reduce 和三元时,我似乎遇到了麻烦
When using using reduce with ternary inside a map, I seem to have troubles
这是 return 一个数字数组,这些数字是基本数组内部数组的最大值。当我使用 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]
如果您的值小于零,则需要删除起始值
x.reduce((a, c) => c > a ? c : a, 0)
^
或使用非常小的起始值,例如 -Number.MAX_VALUE
。
要获得所有最大值中的最大值,您可以减少减少量。如果您只想要最大值,请映射减少量。
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);
不用减,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));
这是 return 一个数字数组,这些数字是基本数组内部数组的最大值。当我使用 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]
如果您的值小于零,则需要删除起始值
x.reduce((a, c) => c > a ? c : a, 0)
^
或使用非常小的起始值,例如 -Number.MAX_VALUE
。
要获得所有最大值中的最大值,您可以减少减少量。如果您只想要最大值,请映射减少量。
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);
不用减,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));