Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

524
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda