Finding Closest Value in an Array

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

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

Get closest value in an Array

I would propose first order on min and take the first value. It's your nearest value and you could do with it what you want. For example calculate nearest-check

int[] testArray = new int[3] { 5, 7, 8 };

int check = 22;

var nearest = testArray.OrderBy(x => Math.Abs(x - check)).First();

Debug.Print(Convert.ToString(nearest-check));

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}

How to find closest number in array above target?

Just fix the code according to your requirement: find the minimal number of those above the target. Also it would make sense to check for null values in the input array.

public static Integer findClosestAbove(Integer[] arr, int target) {
Integer min = null;

for (Integer x : arr) {
if (x != null && x > target && (min == null || min > x)) {
min = x;
}
}
return min; // may be null
}

Similar solution using Java Stream API is as follows:

public static Integer findClosestAboveStream(Integer[] arr, int target) {
return Arrays.stream(arr)
.filter(x -> x != null && x > target)
.min(Integer::compareTo) // Optional<Integer>
.orElse(null); // or orElseGet(() -> null)
}

Test:

Integer[] arr = new Integer[]{1, 2, null, 7, 4};
System.out.println("findClosest:\t" + findClosestAbove(arr, 5));
System.out.println("findClosest2:\t" + findClosestAboveStream(arr, 5));

Output:

findClosest:    7
findClosest2: 7

Finding the closest value in array and remove it

You can do something like this

public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Power: ");
int power = Integer.parseInt(console.nextLine());
ArrayList<Integer> weight = new ArrayList<>();
int averageWagon = 0;
int sum = 0;

while (console.hasNextInt()) {
weight.add(console.nextInt());

}

for (int i = 0; i < weight.size(); i++) {
sum += weight.get(i);
}

if (sum > power) {
averageWagon = sum / weight.size();
//Here I want to find the closest value to averageWagon
int closest = findClosestNumber(averageWagon, weight);
System.out.println("Closest number to average: "+ closest);

}
System.out.println(averageWagon);

System.out.println(weight);
System.out.println(power);
System.out.println(sum);

}

static int findClosestNumber(int num, List<Integer> numbers) {
int closest = numbers.get(0);

for (int i : numbers) {
if (Math.abs(num - i) < Math.abs(num - closest)) {
closest = i;
}
}
return closest;
}

Javascript find closest number in array without going over

You could remove the part that checks for greater.
Another method would be: remove higher values, and get max from remaining ones:

function closest(arr,val){
return Math.max.apply(null, arr.filter(function(v){return v <= val}))
}

console.log(closest([1,22,121223],24)) // prints 22

Find the closest smaller value of an array

If you array is sorted, and small enough, a really simple mode to do what you want it's simplly iterate over the array until number > number-in-array then return the number on the previous position.

function getClosestValue(myArray, myValue){
//optional
var i = 0;

while(myArray[++i] < myValue);

return myArray[--i];
}

Regards.

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. Otherwise undefined is returned.