To split an array in JavaScript, you can use the split method or the slice method.
In this example,
numbers
with elements separated by commas.split
method to split numbers
into an array of strings.split
method returns an array of strings.const numbers = '1,2,3,4,5,6,7,8,9';
const chunks = numbers.split(',');
console.log(chunks);
[ '1', '2', '3', '4', '5', '6', '7', '8', '9' ]
In this example,
numbers
with integer elements.slice
method to split numbers
into slices based on indices.slice
method returns a new array representing the sliced elements.const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const slices = [numbers.slice(0, 3), numbers.slice(3, 6), numbers.slice(6, 9)];
console.log(slices);
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
In this tutorial, we learned How to Split an Array in JavaScript language with well detailed examples.