Created
February 10, 2022 23:21
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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),[[]]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)