How to Split an Array in TypeScript? [With Examples]

As a Typescript developer, you might get requirements to manipulate arrays, such as splitting arrays in TypeScript. In this tutorial, I will explain how to split an array in TypeScript.

Split An Array Using Slice in TypeScript

The simplest way to split an array in TypeScript is by using the slice method. The slice method returns a shallow copy of a portion of an array into a new array object.

Example: Splitting an Array of Names

Consider an array of popular city names in the USA:

let cities: string[] = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Philadelphia", "San Antonio", "San Diego", "Dallas", "San Jose"];

We want to split this array into two smaller arrays.

let firstHalf = cities.slice(0, 5);
let secondHalf = cities.slice(5);

console.log(firstHalf); // ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
console.log(secondHalf); // ["Philadelphia", "San Antonio", "San Diego", "Dallas", "San Jose"]

In this example, the slice method is used to create two new arrays, each containing half of the original array’s elements.

Here is the exact output in the screenshot below:

Split An Array Using Slice in TypeScript

Check out Create a Map from an Array in TypeScript

Splitting TypeScript Arrays by Condition

Sometimes, you may need to split an array in TypeScript based on a specific condition. For instance, you might want to separate even and odd numbers from an array.

Example: Splitting an Array of Numbers

Consider an array of numbers:

let numbers: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

We want to split this array into two arrays: one containing even numbers and the other containing odd numbers.

let evenNumbers = numbers.filter(num => num % 2 === 0);
let oddNumbers = numbers.filter(num => num % 2 !== 0);

console.log(evenNumbers); // [2, 4, 6, 8, 10]
console.log(oddNumbers); // [1, 3, 5, 7, 9]

In this example, the filter method is used to create two new arrays based on the condition provided.

Read How to Find an Object in a TypeScript Array?

Split an Array Using Reduce() Method

The reduce method in TypeScript can be used for more complex splitting logic. It allows you to accumulate values based on custom logic.

Example: Splitting an Array into Chunks

Consider an array of student names:

let students: string[] = ["Alice", "Bob", "Charlie", "David", "Eve", "Frank", "Grace", "Heidi", "Ivan", "Judy"];

We want to split this array into chunks of three students each.

function chunkArray<T>(array: T[], size: number): T[][] {
    return array.reduce((acc, _, i) => {
        if (i % size === 0) acc.push(array.slice(i, i + size));
        return acc;
    }, [] as T[][]);
}

let studentChunks = chunkArray(students, 3);

console.log(studentChunks);
// [["Alice", "Bob", "Charlie"], ["David", "Eve", "Frank"], ["Grace", "Heidi", "Ivan"], ["Judy"]]

In this example, the reduce method is used to create chunks of the specified size.

Here is the exact output in the screenshot below:

Split an Array in TypeScript

Read How to Check Array Equality in TypeScript?

Splitting TypeScript Arrays by Empty Strings

Another common scenario is splitting arrays based on empty strings in TypeScript. This can be particularly useful when dealing with text data.

Example: Splitting an Array by Empty Strings

Consider an array of names with empty strings as separators:

let names: string[] = ["John", "Doe", "", "Jane", "Smith", "", "Emily", "Jones"];

We want to split this array into sub-arrays whenever an empty string is encountered.

function splitByEmptyString(array: string[]): string[][] {
    return array.reduce((acc, val) => {
        if (val === "") acc.push([]);
        else acc[acc.length - 1].push(val);
        return acc;
    }, [[]] as string[][]);
}

let nameGroups = splitByEmptyString(names);

console.log(nameGroups);
// [["John", "Doe"], ["Jane", "Smith"], ["Emily", "Jones"]]

In this example, the reduce method is used to create sub-arrays based on the presence of empty strings.

Check out How to Sort String Arrays in TypeScript?

Split an Array in TypeScript Example: Paginating Data

Pagination is a common feature in web applications, allowing users to navigate through large datasets. Splitting arrays into pages is a practical application of the techniques discussed.

Example: Paginating an Array of Products

Consider an array of product names:

let products: string[] = ["Laptop", "Tablet", "Smartphone", "Monitor", "Keyboard", "Mouse", "Printer", "Camera", "Speaker", "Headphones"];

We want to paginate this array into pages of three products each.

function paginateArray<T>(array: T[], pageSize: number): T[][] {
    return array.reduce((acc, _, i) => {
        if (i % pageSize === 0) acc.push(array.slice(i, i + pageSize));
        return acc;
    }, [] as T[][]);
}

let productPages = paginateArray(products, 3);

console.log(productPages);
// [["Laptop", "Tablet", "Smartphone"], ["Monitor", "Keyboard", "Mouse"], ["Printer", "Camera", "Speaker"], ["Headphones"]]

In this example, the reduce method is used to paginate the array into pages of the specified size.

Conclusion

In this tutorial, I explained how to split arrays in TypeScript using different methods. You can use the slice() method and filter(), and also you can use the reduce() method to split an array in TypeScript.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.