I am working on the code below. Is there a way to get the closet array which are matching in all items with the goal array?
var counts = [
[4,9,15],
[2,11,81],
[20,12,80],
[14,3,80],
[15,6,2],
]
goal = [14,10,70];
var closest = counts.reduce(function(prev, curr) {
return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});
console.log(closest);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can look at it with distances in an n-dimensional space (3 in this case)
var counts = [
[4,9,15],
[2,11,81],
[20,12,80],
[14,3,80],
[15,6,2],
]
goal = [14,10,70];
var best = Infinity;
var closest = null;
for(var i in counts) {
var sum = 0;
for(var j in counts[i]) {
sum += (goal[j] - counts[i][j])**2;
}
if ((sum**.5) < best) {
closest = counts[i];
best = sum**.5;
}
}
console.log(closest);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With