我想与用户打破一个数组:
[
{name: "Carlos"},
{name: "Marcos"},
{name: "Fernando"},
{name: "Jhon"},
{name: "Loius"},
{name: "Jacob"},
]
得到这样的东西:
[
[
{name: "Jhon"},
{name: "Loius"},
{name: "Jacob"},
],
[
{name: "Carlos"},
{name: "Marcos"},
{name: "Fernando"},
]
]
分割它们的标准是我希望每个子数组最多有3个用户,但子数组的数量可以是无限的。
答案 0 :(得分: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));
答案 1 :(得分:2)
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 ())
// [ [ ] ]
&#13;
我认为take
和drop
抽象使得函数读得更好。您的意见可能会有所不同。
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))
答案 2 :(得分:1)
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));
&#13;
.as-console-wrapper{top:0;max-height:100%!important}
&#13;
或
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;
}