หาค่าสูงสุด (Maximum) ในอาร์เรย์ซ้อน (Nested Array) ทุกระดับ ใช้ Recursion
ตัวอย่าง
[34, 65, 67, [43, 76, 87, 23, 56, 7, [54, 7, 87, 23, 79, 994, 2], 54], 54, 4, 2] → Max: 994
ตัวอย่างโค้ด
const getGreatest = (arr, greatest = -Infinity) => {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
const nestedMax = getGreatest(arr[i], greatest);
if (nestedMax > greatest) greatest = nestedMax;
} else if (arr[i] > greatest) {
greatest = arr[i];
}
}
return greatest;
};
ผลลัพธ์
994
ปัญหาของโค้ดต้นฉบับ
return getGreatest(arr[i], greatest) จะ return ทันที ไม่เช็คเอลีเมนต์ที่เหลือในระดับเดียวกัน
เวอร์ชันแก้ไข (Flat + Math.max)
const getGreatest = arr => Math.max(...arr.flat(Infinity));
flat(Infinity) ทำให้อาร์เรย์แบนทั้งหมด แล้ว Math.max(...arr) หาค่าสูงสุด