การใช้งานอื่น:
const arr = ["H", "o", "w", " ", "t", "o", " ", "s", "p", "l", "i", "t", " ", "a", " ", "l", "o", "n", "g", " ", "a", "r", "r", "a", "y", " ", "i", "n", "t", "o", " ", "s", "m", "a", "l", "l", "e", "r", " ", "a", "r", "r", "a", "y", "s", ",", " ", "w", "i", "t", "h", " ", "J", "a", "v", "a", "S", "c", "r", "i", "p", "t"];
const size = 3;
const res = arr.reduce((acc, curr, i) => {
if ( !(i % size) ) {
acc.push(arr.slice(i, i + size));
}
return acc;
}, []);
NB - ไม่ได้แก้ไขอาร์เรย์เดิม
หรือหากคุณต้องการใช้งานได้ 100% ไม่เปลี่ยนรูป (แม้ว่าจะไม่มีอะไรเลวร้ายในการกลายพันธุ์เหมือนที่ทำข้างต้น) และวิธีการที่มีอยู่ในตัว:
function splitBy(size, list) {
return list.reduce((acc, curr, i, self) => {
if ( !(i % size) ) {
return [
...acc,
self.slice(i, i + size),
];
}
return acc;
}, []);
}