Get the Closest Number Out of an Array

Find the number in an array that is closest to a given number

Your example list is sorted. If this is always the case, then binary search for your number. If you don't find the exact number, make the binary search end off by checking the two numbers around where the number would be and return the closest. Be careful with edge cases where all numbers are greater or are all smaller than the target number

If the list isn't always sorted, then go through the list keeping track of the largest number <= the target number and the smallest number >= the target number. Return the one that's closest to the target.

In either solution, you'll need to decide which side to favour if for example you're searching for 2 in [1, 3].

Find closest to the number inside array

If it's sorted in ascending order like in the question this should work.

const floorPerDayMilestones = [25, 50, 75, 100, 125, 150, 175, 200];
const number = 136;

function findClosest(arr, num) {
for (let i = 0; i < arr.length; ++i) {
if (arr[i] > num) {
return arr[i - 1];
}
}
}

console.log(findClosest(floorPerDayMilestones,number));

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 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.

console.log([13, 4, 6, 5, 10, 11].sort((a, b) => a > b).find(x => x > 8));

I want to find the average in a given array, and find the closest number to that average in java

To find the average in the given array and find the number which is closest to the average,

public static void main(String[] args)
{
int array[] = new int[]
{ 1, 2, 3, 4, 5, 6, 7, 8 };
int sum=0;

double avg;
for (int i = 0; i < array.length; i++)
{
sum += array[i];
}
avg = sum / array.length;
System.out.println(avg);

double difference = Math.abs(array[1] - avg);
Integer closest = array[1];
for (int i = 0; i < array.length; i++)
{
double diff = Math.abs(array[i] - avg);
if(difference > diff)
{
difference = diff;
closest = array[i];
}
}
System.out.println(closest);
}

Find closest index of array using 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));

Get closest number of array

You could use this:

// sample arraya = [1, 3, 7, 15, 40, 55, 70, 80, 95]
// get right numberfunction getClosest(a, numberD1) { return numberD1 - a.reduce(function(closest, v) { return numberD1 >= v ? Math.min(numberD1-v, closest) : closest; }, 1e100);}

// output resultdocument.write(8 + ' => ' + getClosest(a, 8));
document.write('<br>');
document.write(54 + ' => ' + getClosest(a, 54));

javascript: closest number in the array on the bigger side

|| 1920 can be added at the end for when .find results in undefined :

var scrSizes = [320, 480, 640, 768, 1024, 1366, 1600, 1920];var scrWidth = 12345;var theSize = scrSizes.find(function(element) { return element > scrWidth; }) || 1920;
console.log(scrWidth, theSize);
var scrWidth = 320;var theSize = scrSizes.find(function(element) { return element > scrWidth; }) || 1920;
console.log(scrWidth, theSize);

Find the index of closest number in array of objects in Javascript

I've just written this code and it seems to work, but it would need to be tested more (it's bigger but maybe more understandable):

const filteredValues = [
{
type1: [],
type2: [
{ w: 86, h: 108, l: 66 },
{ w: 86, h: 109, l: 66 },
],
type3: [{ w: 82, h: 106, l: 73 }],
},
];

function filter(h) {
const keys = Object.keys(filteredValues[0]);
const values = Object.values(filteredValues[0]);
const length = keys.length;
let tempType = keys[0];
let tempClosestHValue = values[0][0]?.h ?? Infinity;
for (let i = 0; i < length; i++) {
const type = values[i];
const key = keys[i];
if (type.length > 0) {
let closestHValue = Math.abs(type[0].h - h);
for (let y = 0; y < values[i].length; y++) {
let data = values[i][y];
if (Math.abs(data.h - h) < closestHValue) {
closestHValue = data.h;
}
}
if (closestHValue < tempClosestHValue) {
tempClosestHValue = closestHValue;
tempType = key;
}
}
}
return tempType;
}

console.log(filter(105));

which returns "type3", but if you modify the h property of the third type to 110, you get "type2" as the output.



Related Topics



Leave a reply



Submit