基于对象子项数量拆分JS数组,类似Lodash _.chunk()但规则不同
Got it, let's build this custom chunking function you're looking for! Unlike Lodash's _.chunk() which splits arrays based on the number of elements, your goal is to group objects by the total count of their sub-items—each group should add up to 3 sub-items total, with the last group taking whatever's left over.
How it works
The core idea is to iterate through your array, keeping track of a "current group" and the total number of sub-items in that group. For each object:
- If adding its sub-items to the current group doesn't exceed 3, we add it to the group and update the total.
- If adding it would push us over 3, we finalize the current group, start a new one with the current object, and reset the total.
- After looping through all objects, we make sure to add the last remaining group to the result.
Code Implementation
Here's a robust, flexible version of the function:
function chunkBySubItemTotal(arr, maxTotal = 3) { const result = []; let currentGroup = []; let currentSubItemTotal = 0; for (const item of arr) { // Safely get the number of sub-items (handle missing/empty subItems) const subItemCount = item.subItems?.length || 0; // Check if adding this item would exceed our max total if (currentSubItemTotal + subItemCount > maxTotal && currentGroup.length > 0) { // Push the full group to results result.push(currentGroup); // Start a new group with the current item currentGroup = [item]; currentSubItemTotal = subItemCount; } else { // Add the item to the current group currentGroup.push(item); currentSubItemTotal += subItemCount; } } // Don't forget to add the last group if it's not empty if (currentGroup.length > 0) { result.push(currentGroup); } return result; }
Test It Out
Let's use a sample array to see how it works:
const sampleItems = [ { subItems: [1, 2] }, // 2 sub-items { subItems: [3] }, // 1 { subItems: [4,5,6] },// 3 { subItems: [7] }, // 1 { subItems: [8,9] } // 2 ]; console.log(chunkBySubItemTotal(sampleItems));
Expected Output:
[ [ { subItems: [1, 2] }, { subItems: [3] } ], // Total: 2 + 1 = 3 [ { subItems: [4, 5, 6] } ], // Total: 3 [ { subItems: [7] }, { subItems: [8, 9] } ] // Total: 1 + 2 = 3 ]
Edge Cases Handled
- Empty input array: Returns an empty array.
- Objects with more than 3 sub-items: They get their own group (since we can't split a single object's sub-items across groups). Example:
const bigItem = [{ subItems: [1,2,3,4] }]; console.log(chunkBySubItemTotal(bigItem)); // [[{ subItems: [1,2,3,4] }]] - Objects with 0 sub-items: They'll be grouped together until adding another would push the total over 3 (though 0s won't contribute to the count, so you could end up with multiple 0-sub-item objects in one group).
内容的提问来源于stack exchange,提问作者Becca
相关产品推荐
相关产品推荐

