[英]Breaking an array of users in a group of sub-arrays
I would like to break a array with users:我想与用户打破一个数组:
[
{name: "Carlos"},
{name: "Marcos"},
{name: "Fernando"},
{name: "Jhon"},
{name: "Loius"},
{name: "Jacob"},
]
And get something like this:得到这样的东西:
[
[
{name: "Jhon"},
{name: "Loius"},
{name: "Jacob"},
],
[
{name: "Carlos"},
{name: "Marcos"},
{name: "Fernando"},
]
]
The criterion for splitting them is that I want that each sub array to have a maximum of 3 users, but the number of sub arrays can be unlimited.拆分它们的标准是我希望每个子数组最多有3个用户,但是子数组的数量可以没有限制。
function splitIntoParts(input, maxElementsPerPart) { const inputClone = [...input]; // create a copy because splice modifies the original array reference. const result = []; const parts = Math.ceil(input.length/maxElementsPerPart); for(let i = 0; i < parts; i++) { result.push(inputClone.splice(0, maxElementsPerPart)); } return result; } console.log(splitIntoParts([ {name: "Carlos"}, {name: "Marcos"}, {name: "Fernando"}, {name: "Jhon"}, {name: "Loius"}, {name: "Jacob"}, {name: "Simon"}, ], 3));
chunk
is elegantly expressed using functional style使用功能风格优雅地表达chunk
const chunk = (xs = [], n = 1) => xs.length <= n ? [ xs ] : [ xs.slice (0, n) ] .concat (chunk (xs.slice (n), n)) const data = [ 1, 2, 3, 4, 5, 6 ] console.log (chunk (data, 1)) // [ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ] ] console.log (chunk (data, 2)) // [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ] console.log (chunk (data, 3)) // [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] console.log (chunk (data, 4)) // [ [ 1, 2, 3, 4 ], [ 5, 6 ] ] console.log (chunk ()) // [ [ ] ]
I think take
and drop
abstractions make the function read a littler nicer.我认为take
and drop
抽象使函数读起来更好一点。 Your opinion may vary.您的意见可能会有所不同。
const take = (xs = [], n = 1) =>
xs.slice (0, n)
const drop = (xs = [], n = 1) =>
xs.slice (n)
const chunk = (xs = [], n = 1) =>
xs.length <= n
? [ xs ]
: [ take (xs, n) ] .concat (chunk (drop (xs, n), n))
let data = [ {name: "Carlos"}, {name: "Marcos"}, {name: "Fernando"}, {name: "Jhon"}, {name: "Loius"}, {name: "Jacob"}, ] function toGroupsOf(n, array){ return Array.from( {length: Math.ceil(array.length/n)}, //how many groups (_,i) => array.slice(i*n, (i+1)*n) //get the items for this group ) } console.log(toGroupsOf(3, data));
.as-console-wrapper{top:0;max-height:100%!important}
or或者
function toGroupsOf(n, array){
var groups = Array(Math.ceil(array.length/n));
for(var i=0; i<groups.length; ++i)
groups[i] = array.slice(i*n, (i+1)*n);
return groups;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.