javascript - How to split an array into 2, left and right -


i have array of menu links ['a','b','c','d','x','y','z'] , want split them array result {'left':['a','b','c','d'], 'right': ['x', 'y','z']}. want them split in half. number of items in list can variable. easiest way this?

you can use array.prototype.slice extract subarrays array:

var arr = ['a','b','c','d','x','y','z'],     mid = math.ceil(arr.length/2),     obj = {         left: arr.slice(0, mid),         right: arr.slice(mid)     }; 

if don't mind altering original array, can use array.prototype.splice:

var arr = ['a','b','c','d','x','y','z'],     obj = {         left: arr.splice(0, math.ceil(arr.length/2)),         right: arr     }; 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -