Skip to content

Array split JavaScript | Example code

  • by

Use the splice() method with a loop to Array split JavaScript. This method adds/removes items to/from an array, and returns the list of removed item(s).

array.splice(index, number, item1, ....., itemN)

You can also use the slice() method to return a new array containing the selected elements.

array.slice(start, end)

Array split JavaScript

A simple example code split the array into 2 parts. The splice() method to split the array into chunks of the array. This method removes the items from the original array.

<!DOCTYPE html>
<html>
<body>
  <script >
    var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
    var res = arr.splice(0,5);

    console.log(res)
    console.log(arr)
  </script>
</body>
</html>

Output:

Array split JavaScript

Just loop over the array, splicing it until it’s all consumed.

var a = ['a','b','c','d','e','f','g']
  , chunk

while (a.length > 0) {
  chunk = a.splice(0,3)
  console.log(chunk)
}

Output:

[ 'a', 'b', 'c' ]
[ 'd', 'e', 'f' ]
[ 'g' ]

Uses the slice() method to split the array into chunks of the array. This method can be used repeatedly to split an array of any size.

This method can extract a slice from the beginning, middle, or end of an array for whatever purposes you require, without changing the original array.

const chunkSize = 10;
for (let i = 0; i < array.length; i += chunkSize) {
    const chunk = array.slice(i, i + chunkSize);
    // do whatever
}

The last chunk may be smaller than chunkSize. For example, when given an array of 12 elements the first chunk will have 10 elements, and the second chunk only has 2.

Note that an chunkSize of 0 will cause an infinite loop.

Do comment if you have any doubts or suggestions on this JS split 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