how can i break an array into a couple

juan field
juan field used Ask the Experts™
on
from this
var arr= [apples, banana, oranges, kiwi];

to this
var newArr = [[apples, banana], [oranges, kiwi]];
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
// this is good , just wanted to hear another opinion. Thank you.


var results = [];
  while (array.length) {
    results.push(array.splice(0, size));
  }
  return results;
Juan, are you having a conversation with yourself :)

I don't see how the comment you posted fits with your question.
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
You can do like this
var arr = ['apples', 'banana', 'oranges', 'kiwi'];
var newarr = [arr.slice(0,2), arr.slice(2)];

Open in new window

The generic version - split any array in two
var arr = ['apples', 'banana', 'oranges', 'kiwi'];
var mid = arr.length >> 1;
var newarr = [arr.slice(0,mid),arr.slice(mid)];

Open in new window

Author

Commented:
thank you so much
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You are most welcome.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial