当前位置:网站首页>Group arrays by a specified size

Group arrays by a specified size

2022-06-11 06:57:00 Xiaoman's code world

Use Array.from() Create a new array , This matches the number of blocks that will be generated . Use Array.slice() Map each element of the new array to size Blocks of length . If the original array cannot be split evenly , Then the final block will contain the remaining elements .

let chunk = (arr, size) => Array.from({
    length: Math.ceil(arr.length / size)
}, (v, i) => arr.slice(i * size, i * size + size));
let arr = [1, 2, 3, 4];
console.log(chunk(arr,2)) //0: Array [ 1, 4 ],1: Array [ 3,4 ],
原网站

版权声明
本文为[Xiaoman's code world]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020525053389.html