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
  const head = copy.splice(0, sizeOfHead)
 
  // return TWO arrays: the first `sizeOfHead` elements and “the rest”
  return [head, copy]
}
 
// 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)
console.log(`${head[0]}, ${head[1]}, and ${rest.length} more`)
// ⇒ "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
  const head = copy.splice(0, sizeOfHead)
 
  // return TWO arrays: the first `sizeOfHead` elements and “the rest”
  return [head, copy]
}
 
// 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)
console.log(`${head[0]}, ${head[1]}, and ${rest.length} more`)
// ⇒ "Bibidi, Babidi, and 1 more"
Debug
none
Grid overlay