gpt4 book ai didi

javascript - 如何从已排序的数组中找到最大的元素?

转载 作者:行者123 更新时间:2023-12-02 17:01:41 24 4
gpt4 key购买 nike

我有三个排序数组,我需要从这些数组中找到前五个“5”元素。我能够找到前两个元素最大元素。我如何找到其他元素?

你能建议我们如何找到其他 3 个元素吗?

这是我的代码

 var maxArray=[];
var array1=[2,7,12,23,40,44,67,88,102]
var array2=[3,12,14,17,23,40,41,67,108]
var array3=[8,12,23,40,59,86,119,130]
var firstMax=array1[array1.length-1];
var secondMax=array2[array2.length-1];


alert(array1[array1.length-1]);
if(array1[array1.length-1]>array2[array2.length-1] && array1[array1.length-1]>array3[array3.length-1]){

maxArray.push(array1[array1.length-1]) ;
firstMax=array1[array1.length-1];
if(array2[array2.length-1]>array3[array3.length-1]){
secondMax=array2[array2.length-1];
}else {
secondMax=array3[array3.length-1];

}
}else if(array2[array2.length-1]>array1[array1.length-1]&& array2[array2.length-1]>array3[array3.length-1]){
maxArray.push(array1[array2.length-1])
firstMax=array2[array2.length-1];

if(array1[array1.length-1]>array3[array3.length-1]){
secondMax=array1[array1.length-1];
}else {
secondMax=array3[array3.length-1];

}

}else{
maxArray.push(array3[array3.length-1])
firstMax=array3[array3.length-1];

if(array2[array2.length-1]>array1[array1.length-1]){
secondMax=array2[array2.length-1];
}else {
secondMax=array1[array1.length-1];

}

}
maxArray.push(secondMax)

alert(maxArray)

fiddle http://jsfiddle.net/9vsjm8uh/

最佳答案

jsFiddle (是的,没有 jQuery 就更好了,谢谢@Rajacsp)

var array1 = [2, 7, 12, 23, 40, 44, 67, 88, 102]
var array2 = [3, 12, 14, 17, 23, 40, 41, 67, 108]
var array3 = [8, 12, 23, 40, 59, 86, 119, 130]

var flatArray = array1.concat(array2).concat(array3);

flatArray.sort(function sortNumber(a, b) { return b - a; });
var maxArray = flatArray.slice(0, 5);

alert(maxArray); // 130,119,108,102,88

关于javascript - 如何从已排序的数组中找到最大的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25649881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com