I am currently available for freelance/contract work. Book a meeting so we can talk about your project.

# Splitting arrays into X elements and “the rest”

Posted on

This little helper can split arrays into the first X elements and “the rest”. You could use it to show the first five photos from a list and a link that says “27 more photos”.

``````// takes an array and the number of elements to extract from the start
const spliceHead = (array, sizeOfHead) => {
// create a copy, because `.splice()` changes the array in place
const copy = [...array]

// cut the first `sizeOfHead` elements from the array and store them

// return TWO arrays: the first `sizeOfHead` elements and “the rest”
}

// this can split an array into “the first three, and everything else”
spliceHead(["John", "Paul", "George", "Ringo"], 3)
// ⇒ [ ["John", "Paul", "George"], ["Ringo"] ]

// we can assign the results to two variables with destructuring
const [head, rest] = spliceHead(["Bibidi", "Babidi", "Boo"], 2)
// ⇒ "Bibidi, Babidi, and 1 more"``````
``````// takes an array and the number of elements to extract from the start
const spliceHead = (array, sizeOfHead) => {
// create a copy, because `.splice()` changes the array in place
const copy = [...array]

// cut the first `sizeOfHead` elements from the array and store them

// return TWO arrays: the first `sizeOfHead` elements and “the rest”
}

// this can split an array into “the first three, and everything else”
spliceHead(["John", "Paul", "George", "Ringo"], 3)
// ⇒ [ ["John", "Paul", "George"], ["Ringo"] ]

// we can assign the results to two variables with destructuring
const [head, rest] = spliceHead(["Bibidi", "Babidi", "Boo"], 2)