The Neighbor Difference

HardAcc. 78.5%
+40 XP 20

Sequential Gaps

The neighbor difference is $|a_i - a_{i+1}|$.

The Assignment

Your function receives an array of numbers.

  1. Use a loop that runs from index 0 to array.length - 2.
  2. For each step, calculate the absolute difference between the current element and the next element.
  3. Add these differences up and print the final sum.

01EXAMPLE 1

Input[1, 5, 2]
Output7

Explanation: |1-5|=4 and |5-2|=3. 4+3=7.

Constraints

  • Stop the loop before the last element to avoid "out of bounds" errors.
  • Use Math.abs() for differences.
ArraysLoopsLogic
JavaScript
Loading...
2 Hidden

Input Arguments

nums[1,5,2]

Expected Output

7

Click RUN to test your solution