Find a matching or closest value in an array
Pass in the number you're searching for as the first parameter and the array of numbers to the second:
function getClosest($search, $arr) {
$closest = null;
foreach ($arr as $item) {
if ($closest === null || abs($search - $closest) > abs($item - $search)) {
$closest = $item;
}
}
return $closest;
}
Find a matching or closest value in an array (from a given value)
% Array to search in, modified to have more than one closest value.
x = [0, 5, 10, 11, 152, 7];
% Target value.
target = 6;
Calculate absolute "distances" between each array element and the target value.
% Temporary "distances" array.
temp = abs(target - x);
Find the minimum "distance" value by min
. Compare the temporary "distances" array to that minimum value (resulting in some binary array), and then use find
to get the corresponding indices, which finally can be used to get the values from the original input array x
.
% Find "closest" values array wrt. target value.
closest = x(find(temp == min(abs(target - x))))
The output looks like this:
closest =
5 7
Find object in array with closest value
You can find the difference between all the numbers and whichever one is closest to zero will be your result, to achieve this I have used .reduce()
with Math.abs()
const data = [ { age: 52 }, { age: 53 }, { age: 54 }, { age: 60 }, { age: 66 }, { age: 72 }, { age: 78 }, { age: 84 } ];
const getAge = (data, target) =>
data.reduce((acc, obj) =>
Math.abs(target - obj.age) < Math.abs(target - acc.age) ? obj : acc
);
console.log(getAge(data, 61)); // {age: 60}
console.log(getAge(data, 50)); // {age: 52}
console.log(getAge(data, -1)); // {age: 52}
console.log(getAge(data, 90)); // {age: 84}
Find nearest value in numpy array
import numpy as np
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
Example usage:
array = np.random.random(10)
print(array)
# [ 0.21069679 0.61290182 0.63425412 0.84635244 0.91599191 0.00213826
# 0.17104965 0.56874386 0.57319379 0.28719469]
print(find_nearest(array, value=0.5))
# 0.568743859261
Matching a number to closest number in a set in Javascript
You could iterate the array and check with the absolute delta and the last delta.
function closestValue(v) { var value, lastDelta;
bandwidthSteps.some(function (a) { var delta = Math.abs(v - a); if (delta >= lastDelta) { return true; } value = a; lastDelta = delta; }); return value;}
var bandwidthSteps = [0.128, 0.256, 0.512, 1, 2, 4, 5, 8, 10, 12, 15, 18, 20, 22, 25, 30, 40, 50, 55, 60, 80, 90, 100, 110, 128, 200, 256, 300, 350, 400, 450, 500];
console.log(closestValue(14));console.log(closestValue(21));
Match values to nearest value in another array in R
We can subtract value
from every element of array
, get the absolute difference and get the index position of minimum value using which.min
.
which.min(abs(array - value))
# [1] 7
finding the nearest number in an array
You can use Array.find()
on sorted array.
The
find()
method returns the value of the first element in the array that satisfies the provided testing function. Otherwiseundefined
is returned.
console.log([13, 4, 6, 5, 10, 11].sort((a, b) => a > b).find(x => x > 8));
find closest index of array in javascript
You could store the index and return this value.
function closest(num, arr) { var curr = arr[0], diff = Math.abs(num - curr), index = 0;
for (var val = 0; val < arr.length; val++) { let newdiff = Math.abs(num - arr[val]); if (newdiff < diff) { diff = newdiff; curr = arr[val]; index = val; } } return index;}
var array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362], number = 155;
console.log(closest(number, array));
Related Topics
How to Set HTML Value Attribute (With Spaces)
How to Push Both Value and Key into PHP Array
PHP Constants Containing Arrays
String Comparison Using '==' Vs. 'Strcmp()'
Force File Download With PHP Using Header()
Upgrading My Encryption Library from Mcrypt to Openssl
List of All Locales and Their Short Codes
Remove New Lines from String and Replace With One Empty Space
Convert Flat Array to a Delimited String to Be Saved in the Database
What's the Difference Between Echo, Print, and Print_R in PHP
Performance of Foreach, Array_Map With Lambda and Array_Map With Static Function