In the question Iterate a list as pair (current, next) in Python, the OP is interested in iterating a Python list as a series of current, next
pairs. I have the same problem, but I'd like to do it in JavaScript in the cleanest way possible, perhaps using lodash.
It is easy to do this with a simple for
loop, but it doesn't feel very elegant.
for (var i = 0; i < arr.length - 1; i++) {
var currentElement = arr[i];
var nextElement = arr[i + 1];
}
Lodash almost can do this:
_.forEach(_.zip(arr, _.rest(arr)), function(tuple) {
var currentElement = tuple[0];
var nextElement = tuple[1];
})
The subtle problem with this that on the last iteration, nextElement
will be undefined
.
Of course the ideal solution would simply be a pairwise
lodash function that only looped as far as necessary.
_.pairwise(arr, function(current, next) {
// do stuff
});
Are there any existing libraries that do this already? Or is there another nice way to do pairwise iteration in JavaScript that I haven't tried?
Clarification: If arr = [1, 2, 3, 4]
, then my pairwise
function would iterate as follows: [1, 2]
, [2, 3]
, [3, 4]
, not [1, 2]
, [3, 4]
. This is what the OP was asking about in the original question for Python.
We can wrap Array.reduce a little to do this, and keep everything clean. Loop indices / loops / external libraries are not required.
If the result is required, just create an array to collect it.
Not sure why you want this but you can just make the "ugly" part on a function and then it looks nice:
You can even slightly modify it to be able to make iterate all i, i+n pairs, not just the next one:
This answer is inspired by an answer I saw to a similar question but in Haskell: https://stackoverflow.com/a/4506000/5932012
We can use helpers from Lodash to write the following:
(Unlike the Haskell equivalent, we need
dropRight
because Lodash'szip
behaves differently to Haskell's`: it will use the length of the longest array instead of the shortest.)The same in Ramda:
Although Ramda already has a function that covers this called aperture. This is slightly more generic because it allows you to define how many consecutive elements you want, instead of defaulting to 2: