I have this array of objects:
[
{ name: 'foo1', speed: 8 },
{ name: 'foo2', speed: 7 },
{ name: 'foo3', speed: 10 },
{ name: 'foo4', speed: 12 },
{ name: 'foo5', speed: 8 },
{ name: 'foo6', speed: 5 }
]
Now I'd like to group the elements of array into chunk based on the "speed" property. If the speed of the current, next and previous elements are <= 10 then the elements should be grouped together. If happens otherwise then another group is created which collects the elements which have speed property >10.
In the end I'd like to have an array of 3 arrays like this:
[
[
{ name: 'foo1', speed: 8 },
{ name: 'foo2', speed: 7 },
{ name: 'foo3', speed: 10 }
], [
{ name: 'foo4', speed: 12 }
], [
{ name: 'foo5', speed: 8 },
{ name: 'foo6', speed: 5 }
]
]
It is important to keep the order of elements, just make them grouped. The length of base array can vary so everything must be dynamically calculated. I've tried to use some loadash methods however I got stuck with no real solution.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…