- 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

Suppose, we have an object of arrays like this −

const obj = { obj1: [ 0, 10 ], obj2: [ 3, 9 ], obj3: [ 5, 12, 14 ] };

We are required to write a JavaScript function that takes in one such object of arrays. Note that each object has more than one distance points, but only one should be chosen to combine with other obj's distance point.

We can combine three objects based on the distance points above in 12 ways.

For example, it could become −

[0,3,5];

In this case, the total distance between three objects would be 5 - 0 which is 5;

Or it can become [10, 9, 5], and the distance is −

10 − 5 = 5;

The combination can also be [0, 3, 12] and the distance is −

12 − 0 = 12;

What we intend to achieve is to find the shortest combination, which in this case should be [10,9, 12]; and the distance is 12−9 =3;

Note that by shortest distance, we mean the difference between the biggest and the smallest element of the group.

The code for this will be −

const obj = { obj1: [ 0, 10 ], obj2: [ 3, 9 ], obj3: [ 5, 12, 14 ] }; const findNearest = (obj = {}) => { let parts = [undefined, undefined, undefined]; let i; let res; const data = Object .values(obj) .map((a, i) => a.map(v => [v, i])) .reduce((a, b) => a.concat(b)) .sort((a, b) => a[0] − b[0] || a[1] − b[1]); for (i = 0; i < data.length; i++) { parts[data[i][1]] = data[i][0]; if (parts.some(v => v === undefined)) continue; if (!res || Math.max(...parts) − Math.min(...parts) < Math.max(...res) − Math.min(...res)) { res = parts.slice(); }; }; return res; }; console.log(findNearest(obj));

And the output in the console will be −

[ 10, 9, 12 ]

- Related Questions & Answers
- Corresponding shortest distance in string in JavaScript
- Shortest Word Distance II in C++
- Shortest Word Distance III in C++
- Program to find distance of shortest bridge between islands in Python
- Program to Find the Shortest Distance Between Two Points in C++
- Shortest Distance to Target Color in C++
- Shortest Distance from All Buildings in C++
- Find the shortest distance between any pair of two different good nodes in C++
- Longest distance between 1s in binary JavaScript
- Hamming Distance between two strings in JavaScript
- JavaScript - find distance between items on array
- Find Shortest distance from a guard in a Bankin Python
- C++ Program to find the Shortest Distance to a character
- Distance between 2 duplicate numbers in an array JavaScript
- Shortest path algorithms in Javascript

Advertisements