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

node.js - How to mock a third-party api calls in the backend -

node.js - Why do I get "SOCKS connection failed. Connection not allowed by ruleset" for some .onion sites? -

matlab - 0-by-1 sym - What do I need to change in order to get proper symbolic results? -