This post will discuss how to conditionally split an array in JavaScript.

Conditionally splitting an array in JavaScript means dividing an array into two or more subarrays based on a certain criterion or function. For example, we may want to split an array of numbers into even and odd numbers, or an array of strings into uppercase and lowercase strings. There are several ways to achieve this, depending on the situation and the desired outcome. Here are some common functions:

1. Using Array.filter() function

The Array.filter() function creates a new array with all the elements that pass a test implemented by a provided function. We can use this function to split an array into two or more arrays based on a condition. For example, if we have an array of numbers and we want to split it into even and odd numbers, we can do this:

Download  Run Code

2. Using Array.reduce() function

The Array.reduce() function applies a function to each element of an array, accumulating the result in a single value. We can use this function to split an array into multiple arrays based on a condition. For example, if we have an array of objects and we want to split it into groups by their category name, we can do this:

Download  Run Code

Output:

{
  A: [
    { id: 1, name: ‘Alexander’, category: ‘A’ },
    { id: 3, name: ‘Evelyn’, category: ‘A’ }
  ],
  B: [
    { id: 2, name: ‘Isabella’, category: ‘B’ },
    { id: 5, name: ‘Emma’, category: ‘B’ }
  ],
  C: [ { id: 4, name: ‘Thomas’, category: ‘C’ } ]
}

3. Using a loop

We can also use a loop to iterate over the array and use a map object to store the subarrays based on a condition. A map object is a collection of key-value pairs that allows us to store any value as a key or a value. For example, if we have an array of strings and we want to split it into subarrays by their length, we can do this:

Download  Run Code

Output:

Map(4) {
  5 => [ ‘A’ ],
  6 => [ ‘B’, ‘C’ ],
  4 => [ ‘D’ ],
  10 => [ ‘E’ ]
}

That’s all about conditionally splitting an array in JavaScript.