在 JavaScript 中查找数组中的第三个最大数字
我们需要编写一个JavaScript函数,它接受一个数字数组作为第一个也是唯一的参数。
我们函数的任务是从数组中选取并返回第三个最大数。如果数组不包含任何第三个最大数,那么我们应该简单地从数组中返回最大数。
例如-
如果输入数组是-
const arr = [34, 67, 31, 87, 12, 30, 22];
那么输出应该是-
const output = 34;
示例
此代码将是-
const arr = [34, 67, 31, 87, 12, 30, 22];
const findThirdMax = (arr = []) => {
const map = {};
let j = 0;
for (let i = 0, l = arr.length; i < l; i++) {
if(!map[arr[i]]){
map[arr[i]] = true;
}else{
continue;
};
arr[j++] = arr[i];
};
arr.length = j;
let result = -Infinity;
if (j < 3) {
for (let i = 0; i < j; ++i) {
result = Math.max(result, arr[i]);
}
return result;
} else {
arr.sort(function (prev, next) {
if (next >= prev) return -1;
return 1;
});
return arr[j - 3]
};
};
console.log(findThirdMax(arr));输出结果控制台中的输出将是-
34