Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!