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?
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?
3 Answers
Reset to default 8You 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)
};
function splitInTwo(arr){
var middle = Math.ceil(arr.length / 2);
return {
left: test.slice( 0, middle ),
right: test.slice( middle )
};
}
var test = ['A','B','C','D','X','Y','Z'];
document.body.innerHTML = JSON.stringify( splitInTwo(test) );