How to compare and perform operations on adjacent items of an array


I’m trying to get my head around using functional language to loop through arrays, but I’m having trouble referring to items before and after the current one while iterating using the higher order functions. How can I (using array.reduce or something else) refer to elements before or after the current item in an iteration? The equivalent of using a for loop to do something, e.g. subtract the second or third value from the first if it’s bigger:

for (var i = 0; i< arr.length; i++) {
   if (arr[i] > arr[i+1]) {

The code you put would work, you just have to make sure i+1 doesn’t go out of bounds (so always bear that in mind when setting your for-loop boundaries).

1 Like