Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an array into 2, left and right

Tags:

javascript

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?

like image 272
iStryker Avatar asked Dec 12 '22 00:12

iStryker


2 Answers

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
    };
like image 121
Oriol Avatar answered Dec 29 '22 01:12

Oriol


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)
    };
like image 33
Yogeshree Koyani Avatar answered Dec 29 '22 01:12

Yogeshree Koyani