function theHighest(data) {
let twoLargest = data.map((x) => {
return x.reduce((prev, curr) => {
return curr
})
})
return twoLargest //returns [3,5,8]
}
console.log(theHighest([[1, 2, 3], [3, 4, 5], [6, 7, 8]]))

上面的函数可以返回每个数组中最大的数字,如果它可以在同一个数组中返回prev和curr,那么就可以完成这项工作,并且可以实现所需的结果,即[2,3,4,5, 7,8] 如何在不使用for循环的情况下返回此内容?
如果我使用for循环,我就是这样做的:
function theHighest(data) {
let highestValues = []
for (let i = 0; i < data.length; i++) {
let first = 0
let second = 0
for (let j = 0; j < data[i].length; j++) {
if (first < data[i][j]) {
second = first;
first = data[i][j];
}
else if (second < data[i][j]) {
second = data[i][j];
}
}
highestValues.push(first, second)
}
return highestValues
}
console.log(theHighest([[1, 2, 3], [3, 4, 5], [6, 7, 8]]))
&#13;
谢谢!
答案 0 :(得分:2)
您可以复制,对数组进行排序并返回两个最大值。
function theHighest(data) {
return [].concat(...data.map(a => a.slice().sort((a, b) => a - b).slice(-2)));
}
console.log(theHighest([[1, 2, 3], [3, 4, 5], [6, 7, 8]]));
答案 1 :(得分:2)
如果数组未排序,您还需要对数组进行排序
function theHighest(data) {
let twoLargest = data.map((x) => {
// Get two largest integers
return x.sort().slice(-2);
})
// Flatten the array
return Array.prototype.concat(...twoLargest);
}
console.log(theHighest([[1, 2, 3], [3, 4, 5], [6, 7, 8]]))
答案 2 :(得分:1)
您还可以使用reduce
和sort
var output = arr.reduce( (a, c) => a.concat(c.sort().slice(-2)), [] );
输出[2,3,4,5,7,8]
<强>演示强>
var arr = [[1, 2, 3], [3, 4, 5], [6, 7, 8]];
var output = arr.reduce( (a, c) => a.concat(c.sort().slice(-2)), [] );
console.log( output );
&#13;