How to batch group of array elements in reference to another array of group size ?
I tried below code.
Code:
var group_size = [1, 3, 5];
var elements = ['a','b','c','d','e','f','g','h','i','j','k','l'];
var output = [];
for (var i=0; i < group_size.length; i++) {
output.push(elements.slice(i, group_size[i]))
}
console.log(output);
Output:
[["a"], ["b", "c"], ["c", "d", "e"]]
But expected output:
[['a'], ['b','c','d'],['e','f','g','h','i'],['j','k','l']]
If there are moe elements, then those elements to be grouped by max group_size element
.
Example :
Input = ['a','b','c']
Output = [['a'], ['b','c']]
Input = ['a','b','c','d','e']
Output = [['a'], ['b','c','d'], ['e']]
Input = ['a','b','c','d','e','f','g','h','i','j','k','l']
Output = [['a'], ['b','c','d'],['e','f','g','h','i'],['j','k','l']]
Input = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p']
Output = [['a'], ['b','c','d'],['e','f','g','h','i'],['j','k','l','m','n'], ['o','p']]
I tried above code but that’s limiting.
How can I do it in ecma5 (js) ?
5
Answers
What do you need for the solution:
Here is the code that will give you the desired result:
Steps:
maxGroupSize
elements
arraymaxGroupSize
as a group sizestartElementIndex
) and the group index(groupIndex
)This code worked with all your provided inputs and should be compatible with es5
Alright here is the best solution, you were right (almost), instead of using
slice
you should have usedsplice
to get the right response, you can read about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/spliceThe code below is exactly the same as yours but just with the correction. Hope this helps.
Use while loop and using max group size when groups out of bounds