- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 ]
- Related Articles
- Compute the differences between consecutive elements and append an array of numbers in Numpy
- Compute the differences between consecutive elements of a masked array in Numpy
- Rearranging elements of an array in JavaScript
- Compute the differences between consecutive elements and prepend & append array of numbers in Numpy
- Counting unique elements in an array in JavaScript
- Constructing an array of smaller elements than the corresponding elements based on input array in JavaScript
- What are the differences between a dictionary and an array in C#?
- Write the differences between atom and elements.
- How to duplicate elements of an array in the same array with JavaScript?
- JavaScript - Constructs a new array whose elements are the difference between consecutive elements of the input array
- Sorting an array including the elements present in the subarrays in JavaScript
- Return an array of all the indices of minimum elements in the array in JavaScript
- Building frequency map of all the elements in an array JavaScript
- JavaScript Checking if all the elements are same in an array
- What are the differences between a list collection and an array in C#?

Advertisements