JavaScript - Constructs a new array whose elements are the difference between consecutive elements of the input array

Javascript LibraryWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of numbers like this −

const arr = [3, 5, 5, 23, 3, 5, 6, 43, 23, 7];

We are required to write a function that takes in one such array and constructs another array whose elements are the difference between consecutive elements of the input array.

For this array, the output will be −

const output = [-2, 0, -18, 20, -2, -1, -37, 20, 16];

Example

Following is the code −

const arr = [3, 5, 5, 23, 3, 5, 6, 43, 23, 7];
const consecutiveDifference = arr => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      if(arr[i + 1]){
         res.push(arr[i] - arr[i+1]);
      };
   };
   return res;
};
console.log(consecutiveDifference(arr));

Output

Following is the output in the console −

[
   -2,   0, -18, 20, -2,
   -1, -37,  20, 16
]
raja
Published on 15-Sep-2020 11:54:44
Advertisements