0

What is the method for breaking up a big array into smaller arrays. Or a big text string into smaller strings in javascript.

Ex: I have a string of 49 words separated by spaces/commas. I want to break it up into smaller strings of 10 words and the 9 remainder string. Same for an 49-element array.

Is there a prebuilt method for this?

TIA

Jamex
  • 1,164
  • 5
  • 22
  • 34
  • Possible duplicate of [Split array into chunks](http://stackoverflow.com/questions/8495687/split-array-into-chunks) – Mogsdad Dec 07 '15 at 15:41

2 Answers2

1

To split up a string, use: string.split. If you want to split a string which is separated by a comma, use string.split(',').

When you want to split a string in parts of 10 characters, use:

var string = "15dsck3c rando mstring esjldf bjk";
var match = string.match(/[\S\s]{10}|[\S\s]{0,9}$/g); //{10} = 10 characters;
var listOfWords = Array.apply(null, match);

Splitting an array can be done by using the array.slice method (which does not modify the array).

var arr = ["big", "small", "huge", "wall", "of", "text", "etc", "etc"];
var newList = [];
for(var i=0, len=arr.length; i<len; i+=10){
    newList.push(arr.slice(i));
}
//newList is an array consisting of smaller arrays, eg 
// [["big", <9 other elements>], [<10 elements>], ...]
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Thanks Rob, your solution would work, I was hoping for a 1 line solution. I guess JS does not have that built in function. – Jamex Sep 29 '11 at 07:48
  • `string.split(",")` is a one line solution. I've just provided multiple solutions in my answer, so that you can choose your preferred method. – Rob W Sep 29 '11 at 07:49
0

http://www.w3schools.com/jsref/jsref_slice_array.asp

a more general tutorial.

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311