JavaScript tracking the differences between elements in an array?


We are given an array of Number literals, and we are required to write a function that returns the absolute difference of two consecutive elements of the array.

For example −

If input array is [23, 53, 66, 11, 67]
Output should be [ 30, 13, 55, 56]

Let’s write the code for this problem −

We will use a for loop that will start iterating from the index 1 until the end of the array and keep feeding the absolute difference of [i] th and [i -1] th element of the original array into a new array. Here’s the code −

Example

var arr = [23, 53, 66, 11, 67]
const createDifference = (arr) => {
   const differenceArray = [];
   for(let i = 1; i < arr.length; i++){
      differenceArray.push(Math.abs(arr[i] - arr[i - 1]));
   };
   return differenceArray;
}
console.log(createDifference(arr));

Output

The output of this code in the console will be −

[ 30, 13, 55, 56 ]

Updated on: 20-Aug-2020

550 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements