- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript - Constructs a new array whose elements are the difference between consecutive elements of the input array
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 ]
Advertisements