Find the closest smaller value of an array

Viewed 5013

I think what I want is pretty simple but I can't really find the correct solution.

I have this kind of array in Javascript :

[0, 38, 136, 202, 261, 399]

And I get a generated value from 0 to 600 on a button click. What I need is to find the nearest lower value in this array.

For example, if the generated value is 198, I want to get 136 as the result. If the generated value is 300, I want 261... If it's 589, I want 399 etc etc.

Until now, I have tried with this code :

var theArray = [ 1, 3, 8, 10, 13 ];
var goal = 7;
var closest = null;

$.each(theArray, function(){
    if (closest == null || Math.abs(this - goal) < Math.abs(closest - goal)) {
        closest = this;
    }
});

alert(closest);

But it only returns the closest value... Now I need the to get only the closest smaller value for the given number... How can I improve my algorithm to fit my needs?

Thanks!

4 Answers

Reverse the array and use find

let arr = [0, 38, 136, 202, 261, 399];
let val = 300;
let number = arr.reverse().find(e => e <= val);
console.log(number);

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.

Another solution is to filter the array to find the closest smaller values and then use the Math.max() function with the spread operator:

// Array to select value
let array = [0, 38, 136, 202, 261, 399];

// Random value
let random = 168;

// Filtering array with closest smaller values [0, 38, 136]
let filtered = array.filter(num => num <= random);

// The closest value will be the maximum
let closest = Math.max(...filtered);

In one line of code:

let closest = Math.max(...array.filter(num => num <= random));

You could use Array#some and exit if the item is greater or equal to the wanted value. Otherwise assign the actual value as return value.

This proposal works for sorted arrays.

function getClosest(array, value) {
    var closest;
    array.some(function (a) {
        if (a >= value) {
            return true;
        }
        closest = a;
    });
    return closest;
}

var array = [0, 38, 136, 202, 261, 399];

console.log(getClosest(array, 100)); //  38
console.log(getClosest(array, 198)); // 136
console.log(getClosest(array, 300)); // 261
console.log(getClosest(array, 589)); // 399

Related