0

I have an array of 60 items. I want to split it into an array within an array of 20 items in it.

Here are the codes that I have, but kind of stuck on how to separate into the array.

const initialData = get(certificate, "transcript", []);
const splitData = [];

This is how the splitTranscriptData should look like at the end

[[1,2,3...20],[21,22,23...40],[41,42,43...60]]

I am trying to make this a dynamic way of separating the initial array into 20 items in each array. For example, my initial array has 55 items, the end result will be 3 arrays with the last one having 15 items in it.

When there are more items in the initial array, let's say 70 items, it will split into 4 arrays with the last one having 10 items in it.

babo
  • 89
  • 1
  • 8

6 Answers6

2

You can use recursion to do this:

const split = (input, output = []) => {
  if (!input.length) return output;
  output.push(input.slice(0, 20))
  return split(input.slice(20), output)
}

const splitData = split(initialData);

Here's a JSFiddle of it working: https://jsfiddle.net/ma63cpbt/5/

This will dynamically split an array of any length into subarrays of length 20, with the last subarray holding any remaining items.

You could also pass in 20 as an argument if you want a different subarray length.

helloitsjoe
  • 6,264
  • 3
  • 19
  • 32
0
var items = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

var splittedData  = [];

function splitData(splitLength) {

    for(var i = 0;i<items.length; i+=splitLength) { 
        splittedData.push(items.slice(i,i+splitLength));        
    }

}

Call:

splitData(4); 

Output:

enter image description here

CoronaVirus
  • 401
  • 2
  • 7
  • 20
0

You can split the array using lodash chunk:

_.chunk(initialData, 20);
Jee Mok
  • 6,157
  • 8
  • 47
  • 80
0

No need to use any library u can easily do it heres the code :)

 const list = [1,2,3,...60]
    const arrayList = [
        list.slice(0,20),
        list.slice(20,40),
        list.slice(40,60),
    ]
0

Array which needs to be splitted

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

Function for splitting

size- size of the chunk. Here it should be 20

    const splittedArray = (arr, size) =>
      arr.length > size
        ? [arr.slice(0, size), ...splittedArray(arr.slice(size), size)]
        : [arr];

Calling the function with array and size of chunk as params

splittedArray(arr, 5)
RS17
  • 773
  • 1
  • 9
  • 23
-1

If it's always going to be 1 x 60 array to a 3 x 20 array, you can hardcode the indices and do it like this:

splitData = [initialData.slice(0,20), initialData.slice(20,40), initialData.slice(40,60)]