Change array list into multiple array lists every 3 items

402 Views Asked by At

I want to filter a large array list into multiple arrays for every 5 items in a certain way so that [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] would be [[1, 2, [3, 4, 5]], [6, 7, [8, 9, 10]]] or [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] would be [[1, 2, [3, 4, 5]], [6, 7, [8, 9, 10]], [11, 12, [13, 14, 15]]]. (All arrays will be a multiple of 5 in my program.)

How would I do this?

Right now I'm doing this

for (var i = 1; i < (stoneTextureUnfiltered.length+1)/1.01; i++) {
    stoneTexture.push([stoneTextureUnfiltered[i], stoneTextureUnfiltered[i+1], stoneTextureUnfiltered[i+2], [stoneTextureUnfiltered[i+3], stoneTextureUnfiltered[i+4], stoneTextureUnfiltered[i+5]]]);
}

but it doesn't seem to be working.

Thanks,

-Voxel

1

There are 1 best solutions below

8
mochaccino On BEST ANSWER

Assuming you've chunked the array already into parts of 5 with these answers and it's stored in a variable named chunks, to wrap the last 3 in each chunk you can use map:

const final = chunks.map((chunk) => [chunk[0], chunk[1], chunk.slice(2)]);

You add the first and second elements to the new list, then add the rest of the chunk as a whole.

Demo below:

// using second answer
var perChunk = 5 // items per chunk    

var inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

var chunks = inputArray.reduce((resultArray, item, index) => { 
  const chunkIndex = Math.floor(index/perChunk)

  if(!resultArray[chunkIndex]) {
    resultArray[chunkIndex] = [] // start a new chunk
  }

  resultArray[chunkIndex].push(item)

  return resultArray
}, [])

// answer below

const final = chunks.map((chunk) => [chunk[0], chunk[1], chunk.slice(2)]);

console.log(final);

As you can see, it works nicely!