Related
JavaScript
I've tried searching for something like this, but I am not able to find it.
It's a simple idea:
a. Take a random number between 0 to 10.
b. Let's say the random number rolled is a 3.
c. Then, save the number (the 3).
d. Now, take another random number again between 0 to 10, but it can't be the 3, because it has already appeared.
One solution is to generate an array (a "bucket") with all the values you want to pick, in this case all numbers from 0 to 10. Then you pick one randomly from the array and remove it from the bucket. Note that the example below doesn't check if the bucket is empty, so if you call the function below more than 10 times you will get an error.
var bucket = [];
for (var i=0;i<=10;i++) {
bucket.push(i);
}
function getRandomFromBucket() {
var randomIndex = Math.floor(Math.random()*bucket.length);
return bucket.splice(randomIndex, 1)[0];
}
// will pick a random number between 0 and 10, and can be called 10 times
console.log(getRandomFromBucket());
using d3:
var bucket = d3.shuffle(d3.range(11));
while(bucket.length) {
console.log(bucket.pop());
}
You can use something like this:
/**
* range Get an array of numbers within a range
* #param min {number} Lowest number in array
* #param max {number} Highest number in array
* #param rand {bool} Shuffle array
* #return {array}
*/
range: function( min, max, rand ) {
var arr = ( new Array( ++max - min ) )
.join('.').split('.')
.map(function( v,i ){ return min + i })
return rand
? arr.map(function( v ) { return [ Math.random(), v ] })
.sort().map(function( v ) { return v[ 1 ] })
: arr
}
And use it like so:
var arr = range( 1, 10, true )
Now you have an array with 10 numbers from 1 to 10 in random order and never repeated. So next you can do this:
arr.forEach(function( num, i ) {
// do something, it will loop 10 times
// and num will always be a different number
// from 1 to 10
});
Just for fun: derived from #Strilles answer a 'bucket constructor'
function RandomBucket(from,until){
min = (Number(from) || 0);
max = (Number(until) || 10)+1;
this.bucket = String(Array(max-min)).split(',').map(function(i){
return min++;
});
if (!RandomBucket.prototype.get){
RandomBucket.prototype.get = function(){
var randomValue =
this.bucket.length < 2
? this.bucket.shift()
: this.bucket.splice(Math.floor(Math.random()*this.bucket.length),1);
return randomValue || 'bucket empty';
};
}
}
See JsFiddle for usage example
Most of the time I'd stick with the method suggested by the other answers - i.e. create an array of possibilities, create a shuffled version of it, then take the first n values as your sample (all operations that are simple and general and can be implemented immutably).
However this isn't great if the range of possibilities is large compared to how much memory you want to use, or compared to how many random values you want to draw (although #Strilles solution uses the memory, but doesn't draw many random values, so is probably the best even for my usecase below).
A solution along the lines your question seems to suggest could look like this:
// select n integers from the range [from, to] (inclusive at both sides),
// don't use this approach for large values of n
// taking random values from the randomSource as needed
function randomNumbersWithoutReplacement(n, from, to, randomSource = Math.random) {
const result = [];
for (let i = 0; i < n; ++i) {
// i values have already been taken
// the +1 makes it inclusive
const rangeWidth = to - from - i + 1
let value = Math.floor(rangeWidth * randomSource()) + from
// correct the value compared to the already sampled integers
for (let j = 0; j < result.length; ++j) {
if (result[j] <= value) {
value++
}
}
result.push(value)
// sorting makes the correction loop simpler
// (and it's nice to report the result sorted too)
result.sort((a, b) => a - b)
}
return result
}
And why might you want this?
const quantumLottoNumbers = randomNumbersWithoutReplacement(6, 1, 59, quantumRandomSource)
Var rnd = getRnd();
While(rnd != lastRnd)
rnd = getRnd();
Where getRnd() is a function that generates your random number.
Actually, you would have to check if your current random number were in an array... And if your list of possible random numbers is small beware of an infinite loop.
Simply use the following function, which will draw a sample between 2 numbers based on sample size, and do so without replacement:
function random_sample_without_replacement(options) {
const arr = [];
while(arr.length < options.sample_size){
var r = Math.floor(Math.random() * options.population_size) + 1;
if(arr.indexOf(r) === -1) {
arr.push(r);
}
}
return(arr)
}
Usage:
random_sample = random_sample_without_replacement({
population_size : 1000,
sample_size : 100
})
[950, 725, 239, 273, 814, 325, 834, 702, 209, 740, 539, 281, 799, 459, 443, 758, 567, 124, 428, 462, 576, 234, 35, 344, 441, 580, 461, 371, 354, 616, 704, 233, 486, 296, 182, 63, 57, 357, 226, 969, 396, 879, 904, 718, 22, 121, 835, 52, 310, 359, 593, 793, 421, 870, 719, 959, 639, 755, 85, 10, 365, 189, 457, 895, 168, 574, 115, 176, 252, 284, 840, 721, 962, 780, 851, 71, 144, 827, 843, 643, 54, 246, 838, 100, 452, 303, 20, 572, 259, 102, 909, 471, 642, 8, 716, 388, 374, 338, 425, 880]
check to see if truly without replacement:
[...new Set(random_sample)].length
100
As a great person (Joma) once said, "Hashmap, I'll use a Hashmap!".
You can simply store the already taken values as object keys, and check every time you take a new one. If it's present you increase it in a loop until it becomes a not taken value. If it reaches the length, set it to zero.
function sample(options, count) {
if (options < count) {
throw new Error(
`Random sample error: can't sample ${count} items without repetition from ${options} options`
);
}
const result = [];
const exclude = {};
for (let i = 0; i < count; i++) {
let index = Math.floor(Math.random() * options);
while (exclude[index]) {
index += 1;
index %= options;
}
exclude[index] = true;
result.push(index);
}
return result;
}
sample(10, 10);
// [8, 4, 6, 5, 7, 9, 0, 1, 3, 2]
sample(10, 3);
// [1, 6, 7]
The computational cost of checking the next index isn't that big cause it uses an object instead of an array.
I don't know if you can determine the needed result size with antecedence, but if not, you can separate the inner for code and the exclude variable. Or even generate the entire sequence and just .pop() new values.
For a large space with picking just two numbers I think you can achieve this without a large array and still uniform probability (and fixed time - no while loop) by picking a number and an offset, something like:
const range = 1000000000;
const firstPick = Math.trunc(Math.random()*range);
// range -1 so the offset won't wrap
const offset= Math.trunc(Math.random()*(range-1));
const secondPick = (firstPick+offset)%range;
And for more than this I think you could accumulate the picks in sorted order and then adjust the subsequent picks by how many numbers were skipped past (if memory efficiency and runtime efficiency mattered) - though it would get more complex.
I want to write a function that takes array as an argument and returns how many numbers can be divided by 12. However, if array has a number higher than 111 then it should return 0;
I wrote this:
function isDivisble(array) {
let numberOfNum = 0;
for(let i=0; i < array.length; i++) {
if(array[i] % 12 == 0 && array[i] < 111) {
numberOfNum = numberOfNum + 1 ;
} else {
numberofNum = 0;
}
}
return console.log(numberOfNum);
}
let test = [12, 24, 36, 44, 55, 255];
isDivisble(test)
I realized that this code checks individually whether the current number is divisible and not higher than 111 and not globally whether the array has a number higher than 111, but I dont understand how to make a general array check.
Is writing for loop with if statement to check and then another for loop inside if statement makes it a little bit spaghetti?
You can use some to check if there is any element which is greater than 111 first.
Then you can use filter to get element that is divisible by 12.
Like this:
const isDivisible = (arr) => {
if (arr.some((e) => e > 111)) return 0;
return arr.filter((e) => e % 12 === 0).length;
};
const test = [12, 24, 36, 44, 55, 48];
console.log(isDivisible(test));
I've slightly modified your function that returns 0 if a number is greater than 111 else it checks if it is divisible by 12
function isDivisble(array) {
let count = 0;
for(let i=0; i<array.length; i++){
if(array[i] > 111){
return 0;
}else{
if(array[i] % 12 === 0){
count++
}
}
}
return count;
}
let test = [12, 24, 36, 44, 55, 255];
console.log(isDivisble(test));
The some array method will do the trick:
array.some(value => { return value > 111 }) will return true if any of its values is greater than 111.
You can also check if every array value respects a certain condition by using array.every with a similar callback:
array.every(value => { return value <= 111 }) is true only if every value in the array is lower than or equal to 111.
The best generic solution is the oene below
Logic
Filter the array for number greater that 111. If this filter returns an array with a length greater than 1 then return 0
Else filter the array for numbers divisible by 12. No need to check number is less than 111. Because if that number is greater than 111 the function might have already returned 0.
Retun the length of the above filter.
Working Fiddle
function isDivisbleGeneric(arr) {
const numberGreaterThanLimit = arr.filter((node) => node > 111);
let returnCount;
if(numberGreaterThanLimit.length > 0) {
returnCount = 0;
} else {
const divisibleBy12 = arr.filter((node) => node %12 === 0);
returnCount = divisibleBy12.length;
}
return returnCount;
}
let test = [12, 24, 36, 44, 55, 255];
const count = isDivisbleGeneric(test);
console.log(count);
One Line Solution
const isDivisbleOneLine = (arr) => arr.filter((node) => node > 111).length > 0 ? 0 : arr.filter((node) => node %12 === 0).length;
let test = [12, 24, 36, 44, 55, 255];
const count = isDivisbleOneLine(test);
console.log(count);
function isDivisble(array) {
// at the beginning, do from here
if (array.some(p=>p > 111)) {
return 0;
}
// Rest xxxxxx
}
Is there a standard method to have special Array which can store last N elements (probably with an internal index to keep current item) such that when it reaches to and pass the last index, it goes to beginning and over-write the most old items. This way we have always the last recent N items. This is useful for example to store recent 10 price values of a product.
I can write a custom function may be like as below but i guess there may be some built-in method for it as it has many uses.
var n = 10; //max number of elements
var a = new Array(n); //init the array
var i = 0; //current position
function setNext(value)
{
i++; if(i >= n) i=0;
a[i] = value;
}
function getLast()
{
return a[i];
}
function getAll()
{
//return concat(a[i+1...n], a[0...i]); //all items from old to new ones
}
Sample data:
// consider n = 10
// assume we set 10 numbers in array,
setNext(101);
setNext(102);
//now a is:
a = [101, 102, 103, 104, 105, 106, 107, 108, 109, 110]; // cur index: 9
//now, if we add another value like as 111, it should take
// position of oldest item of list which is currently 101:
a = [ *111*, 102, 103, 104, 105, 106, 107, 108, 109, 110]; //cur index: 1
You could splice the array and add the last item to the end.
function lastN(limit, array = []) {
if (array.length > limit) array.splice(0, array.length - limit);
const
fluent = {
add: value => {
if (array.length >= limit) array.splice(0, array.length - limit + 1);
array.push(value);
return fluent;
},
getAll: () => array
};
return fluent;
}
const
five = lastN(5),
two = lastN(2, ['a', 'b', 'c', 'd', 'e']);
console.log(...five.getAll());
five.add(0);
console.log(...five.getAll());
five.add(1);
console.log(...five.getAll());
five.add(2);
console.log(...five.getAll());
five.add(3);
console.log(...five.getAll());
five.add(4);
console.log(...five.getAll());
five.add(5);
console.log(...five.getAll());
five.add(6);
console.log(...five.getAll());
five.add(7);
console.log(...five.getAll());
console.log('---')
console.log(...two.getAll());
two.add('f');
console.log(...two.getAll());
two.add('g');
console.log(...two.getAll());
two.add('h');
console.log(...two.getAll());
.as-console-wrapper { max-height: 100% !important; top: 0; }
Not directly, but you could create a function that reads the array and uses the modulo % to perform this operation, something like
const n = 10;
const array = new Array(n);
const get = (a, index) => a(index % a.length);
// all three are the same item
const elem1 = get(array, 1);
const elem2 = get(array, 11);
const elem3 = get(array, 21);
Basically, we are using % to calculate the remainder which would act like a "loop" as you put it:
0 % 10 = 0 // first element
1 % 10 = 1 // second element
...
10 % 10 = 0 // Looped once, gives first element again
11 % 10 = 1 // Looped once, gives the second element
...
20 % 10 = 0 // Looped twice, gives first element again
I am unable to figure out how to write a function that will calculate all possible sums of of the elements of an array, with a max of 4 elements per addition.
Given
x = [1, 32, 921, 9213, 97, 23, 97, 81, 965, 82, 965, 823]
I need to go from (1+32) ~ (965+823) to (1+32+921+9213) ~ (965+82+965+823), calculating all the possible sums.
The output should be an array like this:
{33: [1, 32], 922: [1, 921], .... 2835: [965, 82, 965, 823]}
filled by all the possible sums.
It's not for homework, and what I was looking for is explained down there by Travis J: it was about permutations.
Thanks everybody, I hope this could be useful also to someone else.
jsFiddle Demo
You can use a permutation subset recursive algorithm to find the set of all of the sums and also their combinations.
var x = [1, 32, 921, 9213, 97, 23, 97, 81, 965, 82, 965, 823];
var sums = [];
var sets = [];
function SubSets(read, queued){
if( read.length == 4 || (read.length <= 4 && queued.length == 0) ){
if( read.length > 0 ){
var total = read.reduce(function(a,b){return a+b;},0);
if(sums.indexOf(total)==-1){
sums.push(total);
sets.push(read.slice().sort());
}
}
}else{
SubSets(read.concat(queued[0]),queued.slice(1));
SubSets(read,queued.slice(1));
}
}
SubSets([],x);
console.log(sums.sort(function(a,b){return a-b;}));
//log sums without sort to have them line up to sets or modify previous structure
console.log(sets);
There is a function to generate combinations of k members of a population of n here: https://gist.github.com/axelpale/3118596.
I won't reproduce the function here. You can combine it with another function to sum the combinations generated from an input array, e.g.
// Add combinations of k members of set
function getComboSums(set, k) {
return k_combinations(arr, n).map(function(a){
var sum=0;
a.forEach(function(v){sum += v})
return sum;
});
}
This can be combined with another function to get all combinations from 2 to 4 and concatenate them all together. Note that the total number of combinations in a set of 12 members is 781.
// Add all combinations from kStart to kEnd of set
function getComboSumRange(set, kStart, kEnd) {
var result = [];
for (var i=kStart; i <= kEnd; i++) {
result = result.concat(getComboSums(set, i));
}
return result;
}
Then given:
var arr = [1, 32, 921, 9213, 97, 23, 97, 81, 965, 82, 965, 823];
console.log(getComboSumRange(arr, 2, 4)) // length is 781
The length of 781 agrees with the calculated number of terms based on the formula for finding combinations of k in n:
n! / (k!(n - k)!)
and summing for k = 2 -> 4.
The result looks like:
[33, 922, 9214, 98, 24, 98 ... 2834, 1951, 2835];
You can see the terms start with:
arr[0] + arr[1], arr[0] + arr[2]], ...
and end with:
... arr[7] + arr[9] + arr[10] + arr[11], arr[8] + arr[9] + arr[10] + arr[11]
Array justPrices has values such as:
[0] = 1.5
[1] = 4.5
[2] = 9.9.
How do I return the smallest value in the array?
The tersest expressive code to find the minimum value is probably rest parameters:
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
const min = Math.min(...arr)
console.log(min)
Rest parameters are essentially a convenient shorthand for Function.prototype.apply when you don't need to change the function's context:
var arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
var min = Math.min.apply(Math, arr)
console.log(min)
This is also a great use case for Array.prototype.reduce:
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
const min = arr.reduce((a, b) => Math.min(a, b))
console.log(min)
It may be tempting to pass Math.min directly to reduce, however the callback receives additional parameters:
callback (accumulator, currentValue, currentIndex, array)
In this particular case it may be a bit verbose. reduce is particularly useful when you have a collection of complex data that you want to aggregate into a single value:
const arr = [{name: 'Location 1', distance: 14}, {name: 'Location 2', distance: 58}, {name: 'Location 3', distance: 20}, {name: 'Location 4', distance: 77}, {name: 'Location 5', distance: 66}, {name: 'Location 6', distance: 82}, {name: 'Location 7', distance: 42}, {name: 'Location 8', distance: 67}, {name: 'Location 9', distance: 42}, {name: 'Location 10', distance: 4}]
const closest = arr.reduce(
(acc, loc) =>
acc.distance < loc.distance
? acc
: loc
)
console.log(closest)
And of course you can always use classic iteration:
var arr,
i,
l,
min
arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
min = Number.POSITIVE_INFINITY
for (i = 0, l = arr.length; i < l; i++) {
min = Math.min(min, arr[i])
}
console.log(min)
...but even classic iteration can get a modern makeover:
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
let min = Number.POSITIVE_INFINITY
for (const value of arr) {
min = Math.min(min, value)
}
console.log(min)
Jon Resig illustrated in this article how this could be achieved by extending the Array prototype and invoking the underlying Math.min method which unfortunately doesn't take an array but a variable number of arguments:
Array.min = function( array ){
return Math.min.apply( Math, array );
};
and then:
var minimum = Array.min(array);
I find that the easiest way to return the smallest value of an array is to use the Spread Operator on Math.min() function.
return Math.min(...justPrices);
//returns 1.5 on example given
The page on MDN helps to understand it better: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min
A little extra:
This also works on Math.max() function
return Math.max(...justPrices);
//returns 9.9 on example given.
Hope this helps!
Update: use Darin's / John Resig answer, just keep in mind that you dont need to specifiy thisArg for min, so Math.min.apply(null, arr) will work just fine.
or you can just sort the array and get value #1:
[2,6,7,4,1].sort()[0]
[!] But without supplying custom number sorting function, this will only work in one, very limited case: positive numbers less than 10. See how it would break:
var a = ['', -0.1, -2, -Infinity, Infinity, 0, 0.01, 2, 2.0, 2.01, 11, 1, 1e-10, NaN];
// correct:
a.sort( function (a,b) { return a === b ? 0 : a < b ? -1: 1} );
//Array [NaN, -Infinity, -2, -0.1, 0, "", 1e-10, 0.01, 1, 2, 2, 2.01, 11, Infinity]
// incorrect:
a.sort();
//Array ["", -0.1, -2, -Infinity, 0, 0.01, 1, 11, 1e-10, 2, 2, 2.01, Infinity, NaN]
And, also, array is changed in-place, which might not be what you want.
Imagine you have this array:
var arr = [1, 2, 3];
ES6 way:
var min = Math.min(...arr); //min=1
ES5 way:
var min = Math.min.apply(null, arr); //min=1
If you using D3.js, there is a handy function which does the same, but will ignore undefined values and also check the natural order:
d3.max(array[, accessor])
Returns the maximum value in the given array using natural order. If
the array is empty, returns undefined. An optional accessor function
may be specified, which is equivalent to calling array.map(accessor)
before computing the maximum value.
Unlike the built-in Math.max, this method ignores undefined values;
this is useful for ignoring missing data. In addition, elements are
compared using natural order rather than numeric order. For example,
the maximum of the strings [“20”, “3”] is “3”, while the maximum of
the numbers [20, 3] is 20.
And this is the source code for D3 v4:
export default function(values, valueof) {
var n = values.length,
i = -1,
value,
max;
if (valueof == null) {
while (++i < n) { // Find the first comparable value.
if ((value = values[i]) != null && value >= value) {
max = value;
while (++i < n) { // Compare the remaining values.
if ((value = values[i]) != null && value > max) {
max = value;
}
}
}
}
}
else {
while (++i < n) { // Find the first comparable value.
if ((value = valueof(values[i], i, values)) != null && value >= value) {
max = value;
while (++i < n) { // Compare the remaining values.
if ((value = valueof(values[i], i, values)) != null && value > max) {
max = value;
}
}
}
}
}
return max;
}
ES6 is the way of the future.
arr.reduce((a, b) => Math.min(a, b));
I prefer this form because it's easily generalized for other use cases
var array =[2,3,1,9,8];
var minvalue = array[0];
for (var i = 0; i < array.length; i++) {
if(array[i]<minvalue)
{
minvalue = array[i];
}
}
console.log(minvalue);
Possibly an easier way?
Let's say justPrices is mixed up in terms of value, so you don't know where the smallest value is.
justPrices[0] = 4.5
justPrices[1] = 9.9
justPrices[2] = 1.5
Use sort.
justPrices.sort();
It would then put them in order for you. (Can also be done alphabetically.) The array then would be put in ascending order.
justPrices[0] = 1.5
justPrices[1] = 4.5
justPrices[2] = 9.9
You can then easily grab by the first index.
justPrices[0]
I find this is a bit more useful than what's proposed above because what if you need the lowest 3 numbers as an example? You can also switch which order they're arranged, more info at http://www.w3schools.com/jsref/jsref_sort.asp
function smallest(){
if(arguments[0] instanceof Array)
arguments = arguments[0];
return Math.min.apply( Math, arguments );
}
function largest(){
if(arguments[0] instanceof Array)
arguments = arguments[0];
return Math.max.apply( Math, arguments );
}
var min = smallest(10, 11, 12, 13);
var max = largest([10, 11, 12, 13]);
console.log("Smallest: "+ min +", Largest: "+ max);
I think I have an easy-to-understand solution for this, using only the basics of javaScript.
function myFunction() {
var i = 0;
var smallestNumber = justPrices[0];
for(i = 0; i < justPrices.length; i++) {
if(justPrices[i] < smallestNumber) {
smallestNumber = justPrices[i];
}
}
return smallestNumber;
}
The variable smallestNumber is set to the first element of justPrices, and the for loop loops through the array (I'm just assuming that you know how a for loop works; if not, look it up). If an element of the array is smaller than the current smallestNumber (which at first is the first element), it will replace it's value. When the whole array has gone through the loop, smallestNumber will contain the smallest number in the array.
Here’s a variant of Darin Dimitrov’s answer that doesn’t modify the Array prototype:
const applyToArray = (func, array) => func.apply(Math, array)
applyToArray(Math.min, [1,2,3,4]) // 1
applyToArray(Math.max, [1,2,3,4]) // 4
function tinyFriends() {
let myFriends = ["Mukit", "Ali", "Umor", "sabbir"]
let smallestFridend = myFriends[0];
for (i = 0; i < myFriends.length; i++) {
if (myFriends[i] < smallestFridend) {
smallestFridend = myFriends[i];
}
}
return smallestFridend
}
A super-easy way to find the smallest value would be
Array.prototype.min = function(){
return Math.min.apply(Math,this);
};
To call the function, just use the name of the array and add .min()
Array.prototype.min = function(){
return Math.min.apply(Math,this);
};
var arr = [12,56,126,-1,5,15];
console.log( arr.min() );
If you are using Underscore or Lodash you can get the minimal value using this kind of simple functional pipeline
_.chain([7, 6, -1, 3, 2]).sortBy().first().value()
// -1
You also have the .min function
_.min([7, 6, -1, 3, 2])
// -1
Here is code that will detect the lowest value in an array of numbers.
//function for finding smallest value in an array
function arrayMin(array){
var min = array[0];
for(var i = 0; i < array.length; i++){
if(min < array[i]){
min = min;
}else if (min > array[i]){
min = array[i + 1];
}else if (min == array[i]){
min = min;
}
}
return min;
};
call it in this way:
var fooArray = [1,10,5,2];
var foo = arrayMin(fooArray);
(Just change the second else if result from: min = min to min = array[i]
if you want numbers which reach the smallest value to replace the original number.)
Here is a recursive way on how to do it using ternary operators both for the recursion and decision whether you came across a min number or not.
const findMin = (arr, min, i) => arr.length === i ? min :
findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)
Code snippet:
const findMin = (arr, min, i) => arr.length === i ? min :
findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)
const arr = [5, 34, 2, 1, 6, 7, 9, 3];
const min = findMin(arr, arr[0], 0)
console.log(min);
You can use min method in Math object!
const abc = [50, 35, -25, -6, 91];
function findMin(args) {
return Math.min(...args);
}
console.log(findMin(abc));
For anyone out there who needs this I just have a feeling.
(Get the smallest number with multi values in the array)
Thanks to Akexis answer.
if you have let's say an array of
Distance and ID and ETA in minutes
So you do push maybe in for loop or something
Distances.push([1.3, 1, 2]); // Array inside an array.
And then when It finishes, do a sort
Distances.sort();
So this will sort upon the first thing which is Distance here.
Now we have the closest or the least is the first you can do
Distances[0] // The closest distance or the smallest number of distance. (array).