Jam*_*mes 1 javascript arrays while-loop
我试图找到数字数组中的第二大数字,但最大的数字出现两次,所以我不能只是将其从数组中删除并选择新的最大数字。
array = [0, 3, 2, 5, 5](因此3是第二大值)
我有这段代码,可以显式返回 3,但它不适用于其他数组:
function getSecondLargest(nums) {
var sorted_array = nums.sort(function (a,b) {return a - b;});
var unique_sorted_array = sorted_array.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
return unique_sorted_array[unique_sorted_array.length - 2];
}
return unique_sorted_array[unique_sorted_array.length - 2];
Run Code Online (Sandbox Code Playgroud)
如果我想让它更加动态,有没有一种方法可以识别数组的最大值,然后将其与数组的每次迭代进行比较?
我在想类似的事情:
var greatestNum = sortedArray[-1]
while(greatestNum != i) do {
//check for the first number that doesn't equal greatestNum
}
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激。
您可以简单地先创建一个Set,然后按降序排序并获取第一个索引元素
let array = [0, 3, 2, 5, 5]
let op = [...new Set(array)].sort((a,b) => b-a)[1]
console.log(op)Run Code Online (Sandbox Code Playgroud)
对于那些注重效率的人。IMO这是最好的方法
let array = [0, 3, 2, 5, 5]
let max = -Infinity
let secondMax = -Infinity
for(let i=0; i<array.length; i++){
if(array[i] > max){
secondMax = max
max = array[i]
}
}
console.log(secondMax)Run Code Online (Sandbox Code Playgroud)