ฟังก์ชันรับ rows, cols, initial value คืน 2D array
ตัวอย่างโค้ด
const rows = 4, cols = 5, val = 'Example';
const fillArray = (width, height, value) => {
const arr = Array.apply(null, { length: height }).map(el => {
return Array.apply(null, { length: width }).map(element => {
return value;
});
});
return arr;
};
console.log(fillArray(cols, rows, val));ผลลัพธ์
[ [ 'Example', 'Example', 'Example', 'Example', 'Example' ], [ 'Example', 'Example', 'Example', 'Example', 'Example' ], [ 'Example', 'Example', 'Example', 'Example', 'Example' ], [ 'Example', 'Example', 'Example', 'Example', 'Example' ] ]
คำอธิบาย: Array.apply(null, {length: n}) สร้างอาร์เรย์ว่าง n ช่อง (sparse array) map() เติมค่า แถวละ width คอลัมน์ รวม height แถว
วิธีทันสมัย (ES6): Array.from({length: height}, () => Array.from({length: width}, () => value)) หรือ Array(height).fill().map(() => Array(width).fill(value)) (ระวัง fill reference เดียวกัน)