Function that returns the position of the smallest number in a vector

Asked

Viewed 528 times

0

Simple... I need to know what the position of a value (the lowest value) within a vector, to find the lowest value I am using the Math.min()but to print the result I need to know at which position the value is in the vector. It could be a function that returns the position n in the vector value.

3 answers

1

You can use Array#indexof:

var array = [1,2,3,4,5];
console.log(array.indexOf(2)); // retorna 1

var inputs = document.querySelectorAll("input"); // obtem todos os inputs
var valores = []; // vetor para armanezar somente os valores. Esse vetor será usado para obter o minimo entre um conjunto de valores

// funcao que será chamada pelo botão verificar
function verificar(){
  // forEach itera os inputs do formulario
  inputs.forEach(item =>{  
    if (item.value) // se o valor do input for valido (não vazio, nem espacos em branco, nem NaN, etc
      valores.push(parseFloat(item.value)); // empilha (adiciona) na lista de valores
  });
  var menorValor = Math.min.apply(null, valores); //usamos a função Math min para obter o menor valor de um conjunto de valores
  console.log(valores.indexOf(menorValor));
}
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<button onclick="verificar()">Verificar</button>

1

Use the index text

var arr = [1,2,3];
arr.indexOf(Math.min(...arr));

1


You can use the Math.min.apply to find the lowest value of your array:

var numbers = [1, 5, 0.5, 0.8, 10];
var min = Math.min.apply(null, numbers);

console.log(min);

And to return the position, you can use the index as in the other answers.

Browser other questions tagged

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