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);
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);
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);