ReactHustle

How to Split a Javascript Array by Index

Jasser Mark Arioste

Jasser Mark Arioste

How to Split a Javascript Array by Index

Hello, hustler! In this tutorial, you'll learn how to split a javascript array by index by using Array.prototype.slice method. 

Tutorial Objectives #

In this tutorial, you'll learn the following:

  1. How to split an array by index in javascript
  2. Creating a utility function that extends Array.prototype for reusability
  3. Creating the same reusable utility function in Typescript.

What is Array.prototype.slice() method? #

The Array.prototype.slice method returns a shallow copy of a portion or slice of the array. It accepts two optional arguments start and end to specify which part or piece of the array will be returned.

As you may have guessed, this method is perfect for splitting an array. 

Below are some examples of using the Array.prototype.slice method:

const array = ["a", "b", "c", "d", "e"]

// creating a copy of the array. Call array.slice without arguments
const arr = array.slice() // ["a", "b", "c", "d", "e"]

// slicing the last three elements of an array. We can leave the `end` parameter blank.
// 1. specify a negative index for the `start` parameter
const arr2 = array.slice(-3) //["c", "d", "e")
// 2. start at index 2 all the way to the end.
const arr3 = array.slice(2)

// slicing the first two elements of an array.
// start at index 0 but end in index 1. By default slice method does not include the specified index which is 2.
const arr4 = array.slice(0, 2). //  ["a","b"]
1234567891011121314

Splitting Arrays into two #

Now that you know how to use the Array.prototype.slice method, it's easy to split an array into two.

Suppose, you want to split the array at index 2, where index 2 is included in the first split:

const array = ["a", "b", "c", "d", "e"]
const part1 = array.slice(0,3) // ["a", "b", "c"]
const part 2 = array.slice(3) // ["d", "e"]
123

Suppose, you want to split the array at index 2, where index 2 is included in the second split:

const array = ["a", "b", "c", "d", "e"]
const part1 = array.slice(0,2) // ["a", "b"]
const part 2 = array.slice(2) // ["c", "d", "e"]
123

Creating a reusable splitAt function in Javascript #

Let's create a reusable function Array.prototype.splitAt method.

Array.prototype.splitAt = function(index, includeIndex) {
    const _index = includeIndex?  index+1: index;
    return [this.slice(0,_index), this.slice(_index)]
}
1234

This method accepts an index and returns a new array that contains the split arrays. By extending the Array.prototype object, all your arrays will have access to the splitAt method.

const array = ["a", "b", "c", "d", "e"]
const result = array.splitAt(2) 
console.log(result[0]) // ["a,"b"]
console.log(result[1]) // ["c", "d", "e"]


const result2 = array.splitAt(2, true) //includes the specified index to the first part
console.log(result2[0]) // ["a,"b","c"]
console.log(result2[1]) // ["d", "e"]
123456789

Creating a reusable splitAt function in Typescript #

If you're creating a production application, you're probably using Typescript. However, extending the Array.prototype object requires a few steps. Here's how to do it.

First, let's create a file that extends the Array.prototype definition: lib/array.ts:

// lib/array.ts
// extend the global array interface
declare global {
  interface Array<T> {
    splitAt(index: number, includeIndex?: boolean): T[];
  }
}

// implementation
if (!Array.prototype.splitAt) {
  Array.prototype.splitAt = function <T>(
    this: Array<T>,
    index: number,
    includeIndex?: boolean
  ): T[][] {
    const _index = includeIndex ? index + 1 : index;
    return [this.slice(0, _index), this.slice(_index)];
  };
}

export {};
123456789101112131415161718192021

Now, you can import this file once in your project and it will give you the splitAt method implementation with all the benefits that typescript provides:

// index.ts
import "./lib/array";

const array = ["a", "b", "c", "d", "e"];
const result = array.splitAt(2);
console.log(result[0]); // ["a,"b"]
console.log(result[1]); // ["c", "d", "e"]
1234567

Conclusion #

You learned how to split arrays in javascript and typescript by index. You were able to extend the Array.prototype object and create a reusable function that can be used in the whole application.

If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on GitHub.

Resources #

Credits: Image by Ansgar Scheffold from Pixabay

Share this post!

Related Posts