1

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]]
2

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.