在数组数组的map()中使用reduce()
Using reduce() within map() on array of arrays
我正在进行一个免费的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);
相关文章:
- 对一个对象使用reduce可以返回一个没有't在数组中包含目标字母
- 如果数组中只有一个对象,则Lodash返回错误的reduce结果
- 使用JavaScript's Reduce从对象数组创建数组
- 使用JavaScript映射reduce从数组中删除项
- 使用 reduce 函数返回数组
- 使用 reduce 确定数组中最小数的索引
- 如果对象使用 reduce、forEach 或筛选器共享属性值,则合并 JSON 数组中的对象
- 在数组#reduce中设置初始值与不设置初始值
- 如何仅在数组的某些第一个元素上使用_.reduce
- 为什么这个map reduce Promises数组不起作用,而只是减少它起作用
- 使用reduce来缩短数组
- 在数组数组的map()中使用reduce()
- 使用javascript中的reduce函数查找数组的最小和最大数
- 使用reduce检查数组是否包含与字符串匹配的正则表达式
- 使用reduce (javascript)在数组中添加数字对
- 数组上的Reduce方法-它是如何工作的
- 使用reduce方法处理数组元素
- Javascript-使用reduce来反转数组
- 使用javascript数组.Reduce删除重复项
- 在数组reduce中显式传递未定义的初始值