0

I have the js code below:

let splits = 23;

        

let outer_bound_value = 0;
let data = //this is an array of a large number of predefined objects (10,200+)

 for (i = 0; i < data.length; i = i + outer_bound_value) {
   
   outer_bound_value = data.length / splits;
   let split_arr = array.slice(i, i + outer_bound_value);
   
 }

The desired outcome of this code is to be able to split the mega array into smaller arrays based on what the value of splits is (if splits is 5, split the large array into 5 sections). I think the approach I have above works but it is dependent on splits being able to be go into the length of the object and it could cause outofbounds errors. Anyone have a more efficient way to do what I am trying to do?

Juliette
  • 4,309
  • 2
  • 14
  • 31
  • Why calculate `outer_bound_value` inside the for loop? if you need a list of N elements split into M segments, each segment will be length `floor(N/M)`, except for the last one (which might have 1 more element): you know the lengths already before you start your for loop. – Mike 'Pomax' Kamermans Jun 09 '21 at 22:04
  • @Mike'Pomax'Kamermans do you mind editing my code so i can see what you mean? – Juliette Jun 09 '21 at 22:06
  • So long as `i` is less than array length if the end value of slice() is over length it will handle it without error and only return what is available `console.log([1,2,3,4].slice(1, 100))` – charlietfl Jun 09 '21 at 22:08

1 Answers1

0

First divide the array by the amount of splits you want.

Normally I would use a new Set() as it is much faster than splitting arrays with slice however I have no idea what type of data you have in your arrays, Sets are unique when it comes to ints.

we use recursion and destructuring to return the sliced array. this will return you multiple arrays into the array length/splits.

const splits = 23;

const data = new Array(10000);
const chunkValue = Math.floor(data.length/splits);

function chunkArray(array, size) {
   if(array.length <= size){
       return [array]
   }
   return [array.slice(0,size), ...chunkArray(array.slice(size), size)]
}

const newArrays = chunkArray(data, chunkValue)

Michael Mano
  • 3,339
  • 2
  • 14
  • 35