0%

JS 数组分片切割

问题

期望实现下面的效果 [1, 2, 3, 4, 5, 6, 7] -> [[1, 2, 3], [4, 5, 6], [7]]

实现

lodash

https://lodash.com/docs/#chunk

1
2
3
4
5
_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]

_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]

简单实现

1
2
3
4
5
6
7
8
var i,
j,
temporary,
chunk = 10;
for (i = 0, j = array.length; i < j; i += chunk) {
temporary = array.slice(i, i + chunk);
// do whatever
}

reduce

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var perChunk = 2; // items per chunk

var inputArray = ['a', 'b', 'c', 'd', 'e'];

var result = inputArray.reduce((resultArray, item, index) => {
const chunkIndex = Math.floor(index / perChunk);

if (!resultArray[chunkIndex]) {
resultArray[chunkIndex] = []; // start a new chunk
}

resultArray[chunkIndex].push(item);

return resultArray;
}, []);

console.log(result); // result: [['a','b'], ['c','d'], ['e']]

修改原型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Object.defineProperty(Array.prototype, 'chunk_inefficient', {
value: function (chunkSize) {
var array = this;
return [].concat.apply(
[],
array.map(function (elem, i) {
return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
})
);
},
});

console.log([1, 2, 3, 4, 5, 6, 7].chunk_inefficient(3));
// [[1, 2, 3], [4, 5, 6], [7]]

slice

1
2
3
4
5
6
7
8
9
10
function chunk(array, size) {
// This prevents infinite loops
if (size < 1) throw new Error('Size must be positive');

const result = [];
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size));
}
return result;
}