

- 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
JavaScript - find distance between items on array
Suppose, we have a sorted (increasing order) array of Numbers like this −
const arr = [2, 5, 7, 8, 9];
We are required to write a JavaScript function that takes in one such array. The function should construct a new subarray for each element of the input array.
The sub-array should contain the difference (difference between that very element and the succeeding elements one by one) elements.
Therefore, for the first array element, the differences are −
5 - 2 = 3 7 - 2 = 5 8 - 2 = 6 9 - 2 = 7
Therefore, the subarray for the first element should be −
[3, 5, 6, 7]
Similarly, for the second element, it should be −
[2, 3, 4]
For the third element −
[1, 2]
Fourth −
[1]
And since the fifth is the last element there will be no item left for it, so we are not considering the last element.
Therefore, the output for the full array should be −
const output = [ [3, 5, 6, 7], [2, 3, 4], [1, 2], [1] ];
Example
The code for this will be −
const arr = [2, 5, 7, 8, 9]; const distanceBetween = (arr,r = []) => { if(r.length <= arr.length-2) { let temp = []; let b = arr[r.length]; arr.forEach(e => temp.push(e - b)); r.push(temp.filter(e => e > 0)); return distanceBetween(arr,r); } else { return r; }; } console.log(distanceBetween(arr));
Output
And the output in the console will be −
[ [ 3, 5, 6, 7 ], [ 2, 3, 4 ], [ 1, 2 ], [ 1 ] ]
- Related Questions & Answers
- How to find distance between items on array JavaScript
- Distance between 2 duplicate numbers in an array JavaScript
- Find the least duplicate items in an array JavaScript
- Shortest distance between objects in JavaScript
- 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
- Find the distance covered to collect items at equal distances in Python
- Grouping an Array and Counting items creating new array based on Groups in JavaScript
- Find the minimum distance between two numbers in C++
- Substitute random items in a JavaScript array?
- MongoDB find by multiple array items using $in?
- Find maximum distance between any city and station in C++