I am trying to generate consecutive subarrays but I don't know to do it. Is there someone to help me to do it.
I am student of algorithms in JavaScript
I have this array:
[1,2,3,4,5,6,7,8,9]
I want to return subarrays with size 3 for each using iteration the final result will be:
[1,2,3] [4,5,6] [7,8,9]
I know how to do a subarray using slice(), but as I told I want to do consecutive subarrays with size k.
function ub(a) {
let resposta = []
for ( let i = 0 ; i < a.length; i ) {
resposta = a.slice(2,5)
}
return resposta
}
console.log(ub([2,37,8,9,23,34,44]))
CodePudding user response:
Increment the index by the subarray size each time, then slice that number of elements from the current index on each iteration.
function ub(arr, k) {
let res = [];
for (let i = 0; i < arr.length; i = k) res.push(arr.slice(i, i k));
return res;
}
console.log(JSON.stringify(ub([1,2,3,4,5,6,7,8,9], 3)));
CodePudding user response:
You can use this way
function ub(a) {
return a.reduce((acc, val, index) => {
if (index % 3 === 0) {
acc.push(a.slice(index, index 3));
}
return acc;
}, []);
}
console.log(JSON.stringify(ub([1, 2, 3, 4, 5, 6, 7, 8, 9])));
or you can use Array.from
function ub(a) {
return Array.from({ length: Math.ceil(a.length / 3) }, (_, i) =>
a.slice(i * 3, i * 3 3)
);
}
console.log(JSON.stringify(ub([1, 2, 3, 4, 5, 6, 7, 8, 9])));