ข้อมูลตัวอย่าง
var theValuesIn3DArray = [75, [18, 89], [56, [97], [99]]];
วิธีทำ
ใช้ flat(Infinity) รวมเป็น 1D array แล้ว Math.max(...array)
ตัวอย่างโค้ด
var theValuesIn3DArray = [75, [18, 89], [56, [97], [99]]];
Array.prototype.findTheLargestNumberIn3dArray = function (){
return Math.max(...this.flat(Infinity));
};
console.log("The largest number in 3D array is=");
console.log(theValuesIn3DArray.findTheLargestNumberIn3dArray());
วิธีรัน
node fileName.js
ชื่อไฟล์ demo202.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo202.js The largest number in 3D array is= 99
คำอธิบาย
flat(Infinity) ทำให้ nested arrays ทุกระดับรวมเป็น 1D arrayMath.max(...array) spread operator ส่ง elements เป็น arguments ให้ Math.max
Extend prototype: Array.prototype.methodName ใช้ได้กับทุก arrays (ไม่แนะนำ production)