Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
What is missing to get correct output. I am trying to print Maximum and minimum in the array

When I run this code in browser console or any JavaScript environment, I get max and min as 1,1. Could someone help me to find the error.

var arr = [1,4,6,3];
function maxAndMin(arr) {
var max = arr[0];
var min = arr[0];
for(var i=0; i < arr.lenght; i++) {
  if(arr[i] > max) {
  max = arr[i];
}
  if(arr[i] < min) {
  min = arr[i];
}}
console.log("Max:",max,"Min:",min);
}  

 maxAndMin(arr);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

arr.lenght has a typo, and is returning an undefined back. So you never iterate the for loop.

about 4 years ago · Juan Pablo Isaza Relatório

0

You had a typo with lenhgt. Also, I recommend starting your loop from 1, since the 0'th element is already processed at initialization time.

    var arr = [1,4,6,3];
    function maxAndMin(arr) {
    var max = arr[0];
    var min = arr[0];
    for(var i=1; i < arr.length; i++) {
      if(arr[i] > max) {
      max = arr[i];
    }
      if(arr[i] < min) {
      min = arr[i];
    }}
    console.log("Max:",max,"Min:",min);
    }  

     maxAndMin(arr);

about 4 years ago · Juan Pablo Isaza Relatório

0

if you are using Javascript, then there is an alternate / easy way to find min and max of an array. Its just a one-liner

var arr = [1,4,6,3];

const min = arr.sort((a,b) => a-b)[0];
const max = arr.sort((a,b) => b-a)[0];

console.log('Original Array ==>', arr);
console.log('Min ==>', min);
console.log('Max ==>', max);

this way, you can reduce run time of your function without any for-loops and if-else loops.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda