2015-12-07 51 views
2

我正在研究freecodecamp挑战,并且想知道为什么我的代码不工作以及如何纠正它。在map()中对数组array()使用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]

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

+1

你分配给'innerArray',但不返回任何东西。 –

回答

7

里面的map回调,你应该返回的reduce结果:

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

注有shorter ways of doing that

+0

太好了,谢谢!这真的清除了数组函数的工作方式。 – Tyler

+0

选择这个是正确的,因为即使我的原始方法不是最好的方法,它也能回答我的具体问题。 – Tyler

4

有一个简单的方法

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是罚款。

+0

谢谢,我在map()中使用Math.max很困难,所以我去了reduce()路由。这清除了未来。 – Tyler

1

另一种方式来解决这个

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);