danihazler
danihazler

Reputation: 409

How to split an array in many others arrays with two specific sizes?

I'm trying to find out if there is a way in splitting an array into many others arrays, but these arrays should have a length of 4 and 8. Like:

const someArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25];

output newArray = [[1,2,3,4],
                   [5,6,7,8,9,10,11,12],
                   [13,14,15,16],
                   [17,18,19,20,21,22,23,24],
                   [25]];

I've seen many solutions to chunk into specific single sizes like:

export const chunk = (array, size) => {
  const chunkedArr = [];
  let copiedArr = [...array];
  const numOfChild = Math.ceil(copiedArr.length / size);

  for (let i = 0; i < numOfChild; i++) {
    chunkedArr.push(copiedArr.splice(0, size));
  }
  return chunkedArr;
};

which I've tried to "adapt" for my requirements, but had no success.

Any help? Cheers!

Upvotes: 0

Views: 63

Answers (3)

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

You can use Array.slice() along with appropriate indices to achieve this.

const someArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25];

let i = 0;
let step = 4;
const newArray = [];
while(i < someArray.length) { 
  newArray.push(someArray.slice(i, i + step));
  i += step;
  step = step == 4 ? 8 : 4;
}

console.log(newArray);

Upvotes: 2

maioman
maioman

Reputation: 18744

A simple implementation consuming the array with a recursive function:

const someArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25];


const iter = (sliceLen, arr, acc = []) =>
 arr.length <= sliceLen 
 ? [...acc, arr.slice(0, sliceLen)]
 : iter(sliceLen === 4 ? 8 : 4, arr.slice(sliceLen), [...acc, arr.slice(0, sliceLen)])
 
 const r = iter(4, someArray)
 
 console.log(r)

Upvotes: 2

Taplar
Taplar

Reputation: 24965

One approach to this would be to just swap back and forth between the chunk size for the iteration.

const someArray =  [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25];

console.log(
  chunk(someArray, 4, 8)
);

function chunk(input, size1, size2){
  const output = [];
  let chunkSize = size1;
  
  for (let i = 0; i < input.length;) {
    output.push(input.slice(i).slice(0, chunkSize));
    i += chunkSize;
    chunkSize = (chunkSize === size1 ? size2 : size1);
  }
  
  return output;
}

Upvotes: 0

Related Questions