[英]lodash chunk from end of array
我有一個陣列
const myArray = [1, 2, 2, 2, 3, 3, 3, 4, 4, 4];
我想拆分成更小的數組。 我正在使用lodash chunk來做到這一點。
_.chunk(myArray, 3);
這將回來
[1, 2, 2], [2, 3, 3], [3, 4, 4], [4]
但我希望它能回來
[1], [2, 2, 2], [3, 3, 3], [4, 4, 4]
我的解決方案是這個
_.chain(myArray).reverse().chunk(3).reverse().value()
它會反轉數組,將其拆分然后再次反轉。 但是有更好的方法嗎? 所以chunk從結束而不是從頭開始。
找到余數 ,如果有余數,則從左側切片,並將其與數組其余部分的塊組合。 如果沒有剩余,通常是塊:
const myArray = [1, 21, 22, 23, 31, 32, 33, 41, 42, 43]; const chunkRight = (arr, size) => { const rm = arr.length % size; return rm ? [arr.slice(0, rm), ..._.chunk(arr.slice(rm), size)] : _.chunk(arr, size); }; const result = chunkRight(myArray, 3); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
沒有內置的參數選項(或者像chunkEnd
這樣的單獨方法),但是自己編寫一些能夠在不reverse
數組的情況下實現同樣的東西是微不足道的:
const chunkFromEnd = (arr, size) => { const firstSize = arr.length % size; const result = [arr.slice(0, firstSize)]; for (let i = firstSize; i < arr.length; i += size) { result.push(arr.slice(i, i + size)); } return result; }; console.log(chunkFromEnd([1, 2, 2, 2, 3, 3, 3, 4, 4, 4], 3)); console.log(chunkFromEnd([1, 2, 2, 2, 3, 3, 3, 4, 9, 4, 4, 6, 2, 1], 3));
另一種方法是使用函數reduceRight
。
const myArray = [1, 2, 2, 2, 3, 3, 3, 4, 4, 4]; const chunks = myArray.reduceRight((a, n, i, arr) => { if (((arr.length - 1) - i) % a.chunk === 0) { a.current = []; a.chunks.unshift(a.current); } a.current.push(n); return a; }, { /*This is the size per chunk*/chunk: 3, /*The array with the chunks*/ chunks: [], /*The current array which is being filled*/ current: []}).chunks; console.log(chunks);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.