0

How do I slice an array like this:

var a = [1, 2, 3, 4, 5, 6 , 7, 8];

into thirds (ie. three arrays, like this):

[1, 2, 3]
[4, 5, 6]
[7, 8]

Here's what I've got so far:

var first = a.slice(0, Math.ceil(a.length / 3));
var seconds = ???
var third = ???
Rudiger
  • 6,634
  • 9
  • 40
  • 57

2 Answers2

5

This works, though it can be cleaned up:

var m, n;
var first, second, third;    

m = Math.ceil(a.length / 3);
n = Math.ceil(2 * a.length / 3);

first = a.slice(0, m);
second = a.slice(m, n);
third = a.slice(n, a.length);
Rudiger
  • 6,634
  • 9
  • 40
  • 57
1

First, get the length. Nice and simple: a.length

Next, divide by three and round up. This will be the size of your pieces.

Finally, use a.slice() with appropriate arguments to get the resulting arrays.

Write some code using the above algorithm, and let us know if you have any more specific problems :)

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592