So I've got an array that has thousands of values. The delimiter is the same and the content is all numbers. It's a simple array.

Example..

[491353764,202825540,338196858] 

Imagine that is 15000 values. I need to split the array into multiple groups of 100 strings.

I got the first 100 fine using this:

ids = ids.toString();
ids = ids.split(',', 100);
console.log(ids.toString());

I know this is basic stuff, but I couldn't find anything that would allow me to split it multiple times into groups. Am I focusing on the wrong thing thinking some version of split will do the job? Do I need to put it through a loop?

share|improve this question

Are your numbers in an array or a delimited string? – Sahil Muthoo Feb 17 '12 at 16:59
1  
Do you convert the array to a String on purpose? You could extract the first 100 elements by doing .slice(0,100) which will a. return a new array with the first 100 elements and b. remove those 100 from the original array – m90 Feb 17 '12 at 16:59
@SahilMuthoo The numbers are in that array but have to be converted to groups of 100 strings for the next call. – Brandon Feb 17 '12 at 17:02
@Brandon: Convert them to strings after sliceing the array. – Rocket Hazmat Feb 17 '12 at 17:05
feedback

2 Answers

up vote 4 down vote accepted

I assume you want to store the groups of 100 in another Array...

var ids = [/* your large array of numbers */];

var array_of_sets = [];

while( ids.length ) {
    array_of_sets.push( ids.splice(0, 100) );
}

DEMO: http://jsfiddle.net/rP2Kq/1/

share|improve this answer
Storing the 100 in another group of 100 is fine since. I can just convert it to a string from there. Should (id.splice(0,10) ); be 100 instead? – Brandon Feb 17 '12 at 17:04
@Brandon: Yeah, I already updated. That was for my demo that I added, but forgot to change it back to 100 at first. – am not i am Feb 17 '12 at 17:06
...and if you actually want the result to be strings, then do it in the while loop. array_of_sets.push( ids.splice(0, 100).toString() ); – am not i am Feb 17 '12 at 17:07
Perfect, thanks! Then, I can loop through the array_of_sets to make the next call. – Brandon Feb 17 '12 at 17:08
@Brandon: Yes, you can loop over that Array to access each sub-group. – am not i am Feb 17 '12 at 17:10
show 2 more comments
feedback
var ids = [...];

var splitIds = [];
var splitSize = 100;

for (var j = 0; j < ids.length; j += splitSize) {
    splitIds.push(ids.slice(j, j + splitSize));
}
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.