- 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 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 ]
Advertisements