简体   繁体   中英

How to split an array into 2, left and right

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)
    };

 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) ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM