js 查找数组中倒数第二最大值

发布时间 2023-05-17 14:20:29作者: 生命在于折腾Up
const arr = [1, 5, 3, 7, 9, 21, 33, 18, 12, 44, 43, 22, 55, 66, 65]

const result = arr => {
  // 存储最小值
  let minMax = 0
  // 存储最大值
  let max = 0
  arr.forEach(item => {
    if (item > max) {
      if (minMax < max) {
        minMax = max
      }
      max = item
    } else if (item > minMax) {
      minMax = item
    }
  })
  return [minMax, max]
}
console.log(result(arr))