0

I want to split an array into a group of values starting at the end and leaving the beginning as a remander array. Here's an example of the goal:

arr = [0,1,2,3,4,5,6,7,8,9,10,11]
interval = 5
#chop
output = [[0,1],[2,3,4,5,6],[7,8,9,10,11]]

What's that most efficient way of doing this?

Thanks for any help?

boom
  • 10,856
  • 9
  • 43
  • 64

3 Answers3

3

Can't speak for CoffeeScript, but in JavaScript I don't think there's anything that does that specifically, you'll just need a loop of slice calls. Either loop backward using a negative index (which means "from the end"), or just take the first src.length % interval items on the first pass.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2
var arr = [0,1,2,3,4,5,6,7,8,9,10,11],
    interval = 5,
    output = [];

while (arr.length >= interval) {
    output.unshift(arr.splice(-interval, interval));
}
output.unshift(arr);

console.log(output);
Andreas
  • 21,535
  • 7
  • 47
  • 56
  • 1
    +1, although modifying the original array is unnecessary work (and for all we know, not desirable for other reasons). Note, though, that inferring the second argument like that is a SpiderMonkey extension (not standard), for compatibility you'd need `splice(-interval, interval)`. – T.J. Crowder May 04 '13 at 08:08
  • @T.J.Crowder Added the length part of `.splice()` as mentioned. And for the original array. You're right, but maybe it isn't needed anymore after breaking it up so maybe this could work out. – Andreas May 04 '13 at 08:17
  • I did need to keep the original but I ended up creating a clone and splicing in a similar way. Thanks all. – boom May 04 '13 at 08:32
-1

Reverse. Slice. Push. Reverse.

Dek Dekku
  • 1,441
  • 11
  • 28