让我们说我有一个Javascript数组看起来如下:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?
让我们说我有一个Javascript数组看起来如下:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?
当前回答
我的技巧是使用parseInt(i/chunkSize)和parseInt(i%chunkSize),然后填充数组
// filling items let array = []; for(let i = 0; i< 543; i++) array.push(i); // printing the splitted array console.log(getSplittedArray(array, 50)); // get the splitted array function getSplittedArray(array, chunkSize){ let chunkedArray = []; for(let i = 0; i<array.length; i++){ try{ chunkedArray[parseInt(i/chunkSize)][parseInt(i%chunkSize)] = array[i]; }catch(e){ chunkedArray[parseInt(i/chunkSize)] = []; chunkedArray[parseInt(i/chunkSize)][parseInt(i%chunkSize)] = array[i]; } } return chunkedArray; }
其他回答
超级晚,但我解决了一个类似的问题,使用.join("")的方法将数组转换为一个巨大的字符串,然后使用regex将.match(/.{1,7}/)它转换为最大长度为7的子字符串数组。
const arr = ['abc', 'def', 'gh', 'ijkl', 'm', 'nopq', 'rs', 'tuvwx', 'yz'];
const arrayOfSevens = arr.join("").match(/.{1,7}/g);
// ["abcdefg", "hijklmn", "opqrstu", "vwxyz"]
看看这个在速度测试中如何与其他方法进行比较会很有趣吗
# in coffeescript
# assume "ar" is the original array
# newAr is the new array of arrays
newAr = []
chunk = 10
for i in [0... ar.length] by chunk
newAr.push ar[i... i+chunk]
# or, print out the elements one line per chunk
for i in [0... ar.length] by chunk
console.log ar[i... i+chunk].join ' '
我更喜欢使用splice方法:
var chunks = function(array, size) {
var results = [];
while (array.length) {
results.push(array.splice(0, size));
}
return results;
};
对于功能性的解决方案,使用Ramda:
其中,popularProducts是输入数组,5是数据块大小
导入splitEvery from 'ramda/src/splitEvery' popularProducts splitEvery(5)。Map ((chunk, i) => { //用chunk做一些事情 })
我只是在groupBy函数的帮助下写了这个。
// utils const group = (source) => ({ by: (grouping) => { const groups = source.reduce((accumulator, item) => { const name = JSON.stringify(grouping(item)); accumulator[name] = accumulator[name] || []; accumulator[name].push(item); return accumulator; }, {}); return Object.keys(groups).map(key => groups[key]); } }); const chunk = (source, size) => group(source.map((item, index) => ({ item, index }))) .by(x => Math.floor(x.index / size)) .map(x => x.map(v => v.item)); // 103 items const arr = [6,2,6,6,0,7,4,9,3,1,9,6,1,2,7,8,3,3,4,6,8,7,6,9,3,6,3,5,0,9,3,7,0,4,1,9,7,5,7,4,3,4,8,9,0,5,1,0,0,8,0,5,8,3,2,5,6,9,0,0,1,5,1,7,0,6,1,6,8,4,9,8,9,1,6,5,4,9,1,6,6,1,8,3,5,5,7,0,8,3,1,7,1,1,7,6,4,9,7,0,5,1,0]; const chunks = chunk(arr, 10); console.log(JSON.stringify(chunks));