compact数组取真
- compact(array): 返回数组中所有真值元素组成的新数组
function compact(array) {
return array.filter(item => item)
}
const arr = [9, 0, false, true]
let a = compact(arr)
console.log(a)
chunk数组分块
- chunk(array, size): 将数组拆分成多个 size 长度的区块, 每个区块组成小数组, 整体组成一个二维数组
function chunk(array, size = 1) {
const bigArray = []
let smallArray = []
if (array.length === 0) {
return bigArray
}
if (size < 1) {
size = 1
}
array.forEach(item => {
if (smallArray.length === 0) {
bigArray.push(smallArray)
}
smallArray.push(item)
if (smallArray.length === size) {
smallArray = []
}
});
return bigArray
}
let c = chunk([2, 3, 12, 1, 2, 1, 3, 2, 32, 4, 3, 2, 1, 2], 5)
console.log(c);