0

Suppose that you have an array of doubles in Javascript:

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

What is the most efficient way to convert it into an array of arrays with 2 doubles like above:

double_arr = [[1,2], [3,4], [5,6], [7,8]]
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
chatzich
  • 1,083
  • 2
  • 11
  • 26

1 Answers1

-1

You can iterate skipping one index in each iteration, like this:

const double_arr = [1, 2, 3, 4, 5, 6, 7, 8];

const result = [];

for (let i = 0; i < double_arr.length; i += 2)
  result.push([ double_arr[i], double_arr[i+1] ]);
  
console.log(result);
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
  • @heisenberg If you think a downvote is _"mean"_ than you haven't understood the concept of downvotes. A downvote indicates a problem with the question/answer. Nothing more, nothing less. The DV on this answer is unnecessary. But this answer should not have been added in the first place as there's a valid dupe target (with at least one of the answers being the same as this one). – Andreas Mar 04 '20 at 14:14