Skip to content

Instantly share code, notes, and snippets.

@queviva
Created February 10, 2022 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save queviva/c8f72f45a466a9ebfd9c3ecc1f880eff to your computer and use it in GitHub Desktop.
Save queviva/c8f72f45a466a9ebfd9c3ecc1f880eff to your computer and use it in GitHub Desktop.
slices an array based either on the condition of an element, or just uniformly by quantity
const sliceArrayOnCondition=(a,f)=>a.reduce((x,v,i)=>((isNaN(f)?f(v):i%f===0)&&i!==0?x.push([v]):x.at(-1).push(v),x),[[]]);
@queviva
Copy link
Author

queviva commented Feb 10, 2022

this takes two arguments: first, the array to slice up; then either a function to use for testing the element or just a number that the array will be evenly divided into groups of

so, to split up an array called 'arr' into equal groups of three-elements, you would do this:
sliceArrayOnCondition(arr, 3)

if you want to split it up on every element that is a string, you would do:
sliceArrayOnCondition(arr, v => typeof v === 'string')

or maybe you want to split it up on everything that is an html DOM object:
sliceArrayOnCondition(arr, v => v instanceof Element)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment