Categories
JavaScript Answers

How to split an array into two based on an index in JavaScript?

Spread the love

To split an array into two based on an index in JavaScript, we use the slice method.

For instance, we write

const ar = [1, 2, 3, 4, 5, 6];
const p1 = ar.slice(0, 4);
const p2 = ar.slice(4);

to call ar.slice with 0 and 4 to return an array with the items in ar between index 0 and 3 inclusive.

And we call ar.slice with 4 to return an array with the items in ar from index 4 to the end of the ar array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *