How to find the nearest number with JAVASCRIPT

Asked

Viewed 1,380 times

1

I have a input which receives a user-typed value and an array of 12 values.. I am traversing the array with a Foreach.. because I need to find the approximate value of the value entered in input.. I have the following code:

        $('#possoPagar').keyup(function (e) {
            let valor = $('#possoPagar').val();
            let valorIdeal = 0;

            $.each(parcelas, function (index, item) {
                if (item.valor <= valor && item.valor >= valorIdeal) {
                    valorIdeal = item.valor;

                    $("#vParcela").html(parseFloat(item.valor).toFixed(2).replace('.', ','));
                    nParcelas.val(item.qtdParcelas);
                }
            });
        });

The problem is that while it is less than the value of the parcel it does not recognize that parcel and sometimes it ends up bringing a value that is actually not the most approximate, Thank you!

  • It’s the closest up and down or just down?

  • Post the code so that we can execute and understand what you have already done. Create an example of the problem in jsfiddle or stacksnippet.

2 answers

2

source - brother

var counts = [100, 200, 300, 350, 400, 450, 500, 600, 700, 750, 800, 900],
goal = 320;

var closest = counts.reduce(function(prev, curr) {
  return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});

console.log(closest);

var valores = [100, 200, 300, 350, 400, 450, 500, 600, 700, 750, 800, 900],
valor = 330;

var maisProximo = valores.reduce(function(anterior, corrente) {
  return (Math.abs(corrente - valor) < Math.abs(anterior - valor) ? corrente : anterior);
});

console.log(maisProximo);

reduce() traverse the array from left to right by invoking a return function on each element, or rather, it serves to iterate over an array and use the value of each item to create a final object based on some rule.

Math.abs returns the absolute value of a number

1

This function finds the nearest value, both the smallest and the largest, respectively.

In the function has 2 parameters, ideais and valor, where ideais is an array with ideal values, and valor is the number that the user.

Function:

function valorMaisProximo(ideais, valor) {
    var lo = -1, hi = ideais.length;
    while (hi - lo > 1) {
        var mid = Math.round((lo + hi)/2);
        if (ideais[mid] <= valor) {
            lo = mid;
        } else {
            hi = mid;
        }
    }
    if (ideais[lo] == valor) hi = lo;
    return [ideais[lo], ideais[hi]];
}

Example:

valorMaisProximo([200, 300, 500, 700], 400) // Retorna [300, 500]

I just copied and modified the function a little bit for better understanding, but the source of this code is That Answer Here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.