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

518
Visualizações
isSorted function in Javascript: How to use for-of-loop in the code

I am a beginner in JS writing code, and I have a question about the isSorted function.

I am supposed to use for-of-loop in the code.

Here is the task:

Declare a function isSorted.

/**
 * @param {Array<number>} ??? - an array of numbers
 * @returns {boolean} whether or not the given array is sorted
 */

Here is what i wrote

function isSorted(array) {
  const result = [];
  for (const number of array) {
    if (number < number1 && number2 ) {
      result.push(number);
    }
    return true;
  }
}

Here is the error message that I get

error message

Here is the test that I could not pass with my code above

actual = isSorted([1, 2, 3]);
expected = true;

if (actual === expected) {
  console.log("Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.group("Result:");
  console.log("  actual:", actual);
  console.log("expected:", expected);
  console.groupEnd();
}

actual = isSorted([3, 2, 3]);
expected = false;

if (actual === expected) {
  console.log("Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.group("Result:");
  console.log("  actual:", actual);
  console.log("expected:", expected);
  console.groupEnd();
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can compare the i-th element of the array with the next one. If one element is greater than the following the array is not sorted

function isSorted(array) {
    for (let i = 0; i < array.length; ++i) {
        if (array[i + 1]) {
            if (array[i] > array[i + 1]) {
                return false;
            }
        }
    }
    return true;
}

Or you can reduce your array to a boolean value (see Array.prototype.reduce()):

function isSorted(array) {
    return array.reduce((prev, cur) => prev !== false && cur >= prev && cur)
}

where prev is the the value resulting from the previous iteration and cur the current iteration item.

about 4 years ago · Juan Pablo Isaza Relatório

0

Try this isSorted function:

function isSorted(array) {
  let previousNo = null;
  for (const number of array) {
    if (previousNo != null && number < previousNo) {
      return false;
    }
    previousNo = number;
  }
  return true;
}

It still uses the for..of loop, and here's what it's doing:

  • "previousNo" will store the number that had been looked at during the previous iteration of the loop, so we can see if our current number is less than it. if it is, that means that the numbers are not stored in ascending order, i.e., it isn't sorted (so we return false in this case).
  • If no problems were found in the loop, we return true instead (your version did this as well, the only difference is, you returned true inside the loop, preventing the other items from being checked).
about 4 years ago · Juan Pablo Isaza Relatório

0

This fuction compare array members: first with second, second with third...etc. If the following member of the array is less than the actual, return false(array is not sorted).

function isSorted(array) {
  for (var i = 0; i<array.length; i++) {
      if (array[i] > array[i+1]) {
        return false;
      } 
  }
  return true;
}
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