简体   繁体   English

如何在不使用for循环的情况下从JavaScript数组的每个数组中返回两个最大数?

[英]how to return the two largest number from each array of an array in JavaScript without using for loops?

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

The above function can return the largest numbers in each array and if it could return prev along with curr in the same array the job would be done and the desired result would be achieved which is [2,3,4,5,7,8] How can I return this without using for loops at all? 上面的函数可以在每个数组中返回最大的数字,如果可以在同一个数组中返回prev和curr,则将完成该工作,并且将获得期望的结果,即[2,3,4,5,7,8 ]我如何不使用for循环就返回它?

If I use for loops here is how I do it: 如果我使用循环,请按以下步骤操作:

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

Thank you! 谢谢!

You could take a copy, sort the array and return the two max values. 您可以进行复制,对数组进行排序并返回两个最大值。

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

You need to sort the array as well if it not sorted 您还需要对数组进行排序(如果未排序)

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

You can also use reduce and sort 您还可以使用reducesort

var output = arr.reduce( (a, c) => a.concat(c.sort().slice(-2)), [] );

outputs [2,3,4,5,7,8] 输出[2,3,4,5,7,8]

Demo 演示版

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM