0

I have an array containing 4 values. I need to make it a nested array with two arrays containing two values. Javascript is needed. This answer could help but it is in Ruby. Array reduce may help but I am not able to use it well enough.

array = [20, 45, 22, 51]
result = [[20,45],[22,51]]
lekythos
  • 113
  • 1
  • 8
  • (as well as many more [Split array into chunks of N length](https://stackoverflow.com/questions/11318680/split-array-into-chunks-of-n-length), [How to split a long array into smaller arrays, with JavaScript](https://stackoverflow.com/questions/7273668/how-to-split-a-long-array-into-smaller-arrays-with-javascript) etc. etc.) – pilchard May 10 '22 at 21:51
  • https://lodash.com/docs/4.17.15#chunk – Ethaan May 10 '22 at 21:52

1 Answers1

0

Use map and slice

const array = [20, 45, 22, 51]

const mid = Math.floor(array.length / 2);

const result = [[0, mid], [mid, array.length]].map(idxs => array.slice(...idxs))

console.log(result)
Siva K V
  • 10,561
  • 2
  • 16
  • 29