Is there an elegant, functional way to turn this array:
[ 1, 5, 9, 21 ]
into this
[ [1, 5], [5, 9], [9, 21] ]
I know I could forEach
the array and collect the values to create a new array. Is there an elegant way to do that in _.lodash
without using a forEach
?
You could map a spliced array and check the index. If it is not zero, take the predecessor, otherwise the first element of the original array.
An even shorter version, as suggested by Bergi:
Here's
slide
which has two parameters to control the size of the slice and how many elements are dropped between slicesslide
differs from other answers here by giving you these control parameters. other answers here are limited to producing only a slices of 2, or incrementing the slice by 1 each timeIf for some reason you didn't want
slide
to include partial slices, (slices smaller thanm
), we could edit it as suchI'm sure there is an elegant way, programmatically, but, mathematically I can't help seeing that each new pair has an index difference of 1 from the original array.
If you (later) have the need to turn your array
[ 1, 5, 9, 21, 33 ]
into[ [1, 9], [5, 21], [9, 33] ]
, you can use the fact that the difference between the indices is 2.If you create code for the index difference of 1, extending this would be easy.
I noticed that the current solutions, in a way, all look ahead or behind (
arr[i + 1]
orarr[i - 1]
).It might be useful to also explore an approach that uses
reduce
and an additional array, defined within a function's closure, to store a to-be-completed partition.Notes:
part
doesn't have to be an array when working with only 2 items, but by using an array, we extend the method to work forn
-sized sets of itemsshift
, you can use a combination ofslice
and redefinepart
, but I think it's safe here.length
less than the required number of elements are not returnedYou may do as follows with just a sinle liner of
.reduce()
with no initial;This is easily done with
array.reduce
. What the following does is use an array as aggregator, skips the first item, then for each item after that pushes previous item and the current item as a pair to the array.An expanded version would look like: