I have created a versatile function that is capable of handling various scenarios based on your needs. You have the option to configure it to accommodate any number of objects by simply passing in the parameter n
.
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function splitListByN(list, n = 2, reverse) {
if(reverse) {
return [list.splice(list.length - n).reverse()].concat(list.length > 0 ? splitListByN(list, n, reverse) : list);
}
return [list.splice(0, n)].concat(list.length > 0 ? splitListByN(list, n) : list);
}
console.log(splitListByN(items, 3));
The function works by breaking down the initial list into smaller partitions. Each partition includes
[firstPartition, shortenedListFromRecursiveCall]
. For instance, with
n
set to 3, the output will be
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
. If no value is provided for
n
, it defaults to 2.
Furthermore, you can utilize the reverse feature:
console.log(splitListByN(items, 3, true))
. This would result in
[ [ 10, 9, 8 ], [ 7, 6, 5 ], [ 4, 3, 2 ], [ 1 ] ]