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

206
Vistas
how to sort array by last digit?

I am required to write a function that receives an array of numbers and should return the array sorted using for the comparison of their last digit, if their last digit is the same you should check the second to last and so on.

Example:

Input: [1, 10, 20, 33, 13, 60, 92, 100, 21]

Output: [100, 10, 20, 60, 1, 21, 92, 13, 33]

but I get

Output: [ 10, 20, 60, 100, 1, 21, 92, 33, 13 ]

my code:

/**I guess the input numbers are only integers*/
input = [1, 10, 20, 33, 13, 60, 92, 100, 21];

const reverseString = (string) => {
  const stringToArray = string.split("");
  const reversedArray = stringToArray.reverse();
  const reversedString = reversedArray.join("");
  return reversedString;
};

let sortedInput = input.sort((firstNumber, secondNumber) => {
  const firstNumberReversed = reverseString(firstNumber.toString());
  const secondNumberReversed = reverseString(secondNumber.toString());
  const largerOne = Math.max(
    firstNumberReversed,
    secondNumberReversed
  ).toString;

  for (let i = 0; i < largerOne.length; i++) {
    if (firstNumberReversed[i] != secondNumberReversed[i]) {
        if(firstNumberReversed[i] > secondNumberReversed[i]){
            return 1
        }
        if(secondNumberReversed[i] > firstNumberReversed[i]){
            return -1
        }
    }
  }
});

console.log(sortedInput);

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can do this using the Remainder Operator:

Demo:

const data = [1, 10, 20, 33, 13, 60, 92, 100, 21];

data.sort((a, b) => {
  for (let i = 1, sum = a + b; ; i *= 10) {
    const diff = (a % i) - (b % i);
    if (diff === 0 && i < sum) continue;
    return diff;
  }
});

console.log(data);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can achieve this result if you sort it after reversing the number

const arr = [1, 10, 20, 33, 13, 60, 92, 100, 21];

const result = arr
  .map((n) => [n, n.toString().split("").reverse().join("")])
  .sort((a, b) => a[1].localeCompare(b[1]))
  .map((a) => a[0]);

console.log(result);

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