How to find the closest number with JAVASCRIPT

0

I have a input which receives a value entered by the user and an array with 12 values .. I'm traversing the array with a ForEach .. since I need to find the approximate value of the value typed 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 installment it does not recognize that portion and sometimes it ends up bringing a value that is not really the closest, Thanks!

    
asked by anonymous 02.10.2017 / 02:30

2 answers

1

This function finds the closest value, either the smallest or the largest, respectively.

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

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 for a better understanding, but the source of this code is This Answer Here

    
02.10.2017 / 03:09
1

font - 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 () traverses the left array to right invoking a return function on each element, or rather, iterates over an array and uses the value of each item to create a final object based on some rule.

     

Math.abs returns the absolute value of a number

    
02.10.2017 / 05:20