Devuelve la posición de matriz del número más bajo (no negativo)

I need to return the position of the element closest to zero without being a negative number.

I have 4 roll sizes(in") to cut film from. I'm trying to enter a width variable and subtract from the elements of the array and the closest to 0 will return the array position of the best roll size. I hope this makes sense. Thanks.

  var width = ""

var rollArray = [36, 48, 60, 72]
            var newArray = []
            for(i in rollArray){ newArray.push ((rollArray[i]) - width) }

alert(newArray);

returns width minus each element, now I need to find how to return the lowest values array position so that I can get the roll size from the equivalent rollArray position.

preguntado el 01 de febrero de 12 a las 03:02

Note as a matter of proper practice, don't use for-in for iterating an array in JavaScript. It's purpose is iterating over object properties. Instead do for (var i=0; i<rollArray.length; i++) If any props or methods get added to the Array prototype, you'll get odd results from the for-in. -

So using your example, what did you want returned? 0 since 36 is the closest to zero? -

3 Respuestas

var width = 41;
var rollArray = [36, 48, 60, 72];
var closest = rollArray.filter(function(ele){return ele-width >= 0}).sort()[0];

Respondido 01 Feb 12, 07:02

GENIUS, great! Much appreciated! - user1181825

var width = ""

var rollArray = [36, 48, 60, 72]
            var newArray = []
            var min=1000000 //a very large number that you know it's larger than (rollArray[i]) - width)
            var minIndex=-1
            for (var i=0; i<rollArray.length; i++){ newArray.push ((rollArray[i]) - width) 
            if (min< rollArray[i]) - width &  rollArray[i]) - width >0)
            {
                            min = rollArray[i]) - width;
                            minIndex = i;
            }
}
alert (minIndex);
alert(newArray);

Respondido 01 Feb 12, 07:02

there are easier ways than that. But it is an interesting approach - ajax333221

var width = 37;
var rollArray = [36, 48, 60, 72];
var closest = null;
for (var i=0; i<rollArray.length; i++)
{
    if (rollArray[i] >= width)
    {
        if (closest == null || rollArray[i] <= rollArray[closest])
        {
            closest = i;
        }
    }
}

Respondido 01 Feb 12, 08:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.