# Shortest distance between objects in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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.

## Example

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));

## Output

And the output in the console will be −

[ 10, 9, 12 ]
Updated on 25-Nov-2020 11:39:50