0

I can solve this problem in a few different ways, but I am not sure if there is a more elegant way to do so.

Take an array

let foo = [1,2,3,4,5]

Is there a method using array destructuring that would work like thist:

split(array, n) =>
  ...

let bar = split(foo, 3)
bar[0] = [1,2,3]
bar[1] = [4,5]

I don't know n coming into the problem. I feel like this should be doable with destructuring, but the way I am reading it I do not see how to do so.

Matt
  • 2,795
  • 2
  • 29
  • 47
  • So, you want to split an array into chunks? http://stackoverflow.com/questions/8495687/split-array-into-chunks – mikemike May 12 '15 at 20:36
  • @mikemike Not precisely. I want the first piece to be of size 0-n, and a second that is whatever remains, no matter size. – Matt May 12 '15 at 20:52
  • You'd just use `slice` twice. There's no native `partition` method in js – Bergi May 13 '15 at 15:09

2 Answers2

2

If you are ok with declaring n variables and then merging them into an array, you could use destructuring assignment :

const [a, b, ...rest] = [10, 20, 30, 40, 50];

console.log([a,b], rest);
// expected output: [10,20] [30,40,50]
golfadas
  • 5,351
  • 3
  • 32
  • 39
0

You should return array with two arrays. Then you can use destructuring to assign parts to different variables

split(array, n) =>
  return [array.slice(0, n), array.slice(n)]

let foo = [1,2,3,4,5]
let [bar, baz] = split(foo, 3)
console.log(bar) // [1,2,3]
console.log(baz) // [4,5]

Here is a Babel REPL where you can try it out

just-boris
  • 9,468
  • 5
  • 48
  • 84