Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การหาตัวเลขที่มากที่สุดในอาร์เรย์ที่มีชนิดข้อมูลผสมใน JavaScript

คำอธิบาย

หาตัวเลขที่มากที่สุดในอาร์เรย์ที่มีทั้งตัวเลข สตริง และค่า falsy ต่างๆ

ตัวอย่าง

[23, 'hello', undefined, null, 21, 65, NaN, 1, undefined, 'hii'] → 65

ตัวอย่างโค้ด

const arr = [23, 'hello', undefined, null, 21, 65, NaN, 1, undefined, 'hii'];

const pickBiggest = arr => {
  let max = -Infinity;
  for (let i = 0; i < arr.length; i++) {
    if (!+arr[i]) {
      continue;
    }
    max = Math.max(max, +arr[i]);
  }
  return max;
};

console.log(pickBiggest(arr));

ผลลัพธ์

65