I have an array of menu links ['A','B','C','D','X','Y','Z']
and I want to split them into an array with this result {'left':['A','B','C','D'], 'right': ['X', 'Y','Z']}
. I want them split in half. The number of items in the list can variable. What is the easiest way to do this?
You can use Array.prototype.slice
to extract subarrays from an 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 you don't mind altering the original array, you can also 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
};
Split array into two parts with slice
function.
var numbers= [1,2,3,4,5,6,7,8,9,10],
leftEnd= Math.ceil(numbers.length/2),
result= {
left: numbers.slice(0,leftEnd),
right: numbers.slice(leftEnd)
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With