

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find distance between items on array JavaScript
We are required to write a function, say arrayDistance() that takes in an array of Numbers and returns another array with elements as the difference between two consecutive elements from the original array.
For example, if the input array is −
const arr = [1000,2000,5000,4000,300,0,1250];
Then the output would be −
[(1000-2000),(2000-5000),(5000-4000),(4000-300),(300-0),(0-1250)]
Therefore, let’s write the code for this function −
Example
const arr = [1000,2000,5000,4000,300,0,1250]; const arrayDistance = arr => { return arr.reduce((acc, val, ind) => { if(arr[ind+1] !== undefined){ return acc.concat(Math.abs(val-arr[ind+1])); }else{ return acc; } }, []); }; console.log(arrayDistance(arr));
Output
The output in the console will be −
[ 1000, 3000, 1000, 3700, 300, 1250 ]
- Related Questions & Answers
- JavaScript - find distance between items on array
- Distance between 2 duplicate numbers in an array JavaScript
- Find the least duplicate items in an array JavaScript
- Shortest distance between objects in JavaScript
- Find the distance covered to collect items at equal distances in Python
- How to display JavaScript array items one at a time in reverse on button click?
- Longest distance between 1s in binary JavaScript
- Hamming Distance between two strings in JavaScript
- Display array items on a div element on click of button using vanilla JavaScript
- MongoDB find by multiple array items?
- Implement $dateToString on array items with MongoDB
- Grouping an Array and Counting items creating new array based on Groups in JavaScript
- How to set the distance between lines in a text with JavaScript?
- How to find the absolute distance between columns of an R data frame?
- Find the minimum distance between two numbers in C++
Advertisements