Skip to content

JavaScript split array into two | Example code

  • by

Find the middle index of the array using the length/2 and Math ceil() method and then use this middle index and Array splice() method to split the array into two in JavaScript.

var half_length = Math.ceil(arrayName.length / 2);    

var leftSide = arrayName.slice(0,half_length);

JavaScript split array into two

Simple example code.

  • list.splice(0, middleIndex) removes the first 3 elements starting from 0 indexes from an array and returns it.
  • list.splice(-middleIndex) removes the last 3 elements from an array and returns it.
<!DOCTYPE html>
<html>
<body>
  <script >
    const arr = [1, 2, 3, 4, 5, 6];
    const middleIndex = Math.ceil(arr.length / 2);

    const f = arr.splice(0, middleIndex);   
    const s = arr.splice(-middleIndex);

    console.log(f);  
    console.log(s);
    console.log(arr); 
  </script>
</body>
</html>

Output:

JavaScript split array into two

If you don’t want to change the original array, this can also be done by chaining Array.slice() method with Array.splice().

const list = [1, 2, 3, 4, 5, 6];
const middleIndex = Math.ceil(list.length / 2);

const f= list.slice().splice(0, middleIndex);   
const s= list.slice().splice(-middleIndex);

console.log(f);  // [1, 2, 3]
console.log(s); // [4, 5, 6]
console.log(list); // [1, 2, 3, 4, 5, 6];

Do comment if you have any doubts or suggestions on this Js array topic,

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading