1

const num = 12345

for (var i = 0; i < num.length; i++) {
  const j = i + 1
  if (num.charAt(i) < num.charAt(j)) {

    num.replace(i, j)
  }
}

console.log(num)

I'm trying to make a function that replace sort() method by javascript.

I want to sort my number from highest to lowest inside the variable num and return it after change. Here I'm using for loop with j so I'll be able to compare the indexes and change num but something wrong what do I miss?

I would love to keep it simple for my understanding.. thanks to the helpers!

7
  • 'but something wrong'... and what is wrong? Commented Aug 26, 2020 at 11:45
  • num.length returns undefined Commented Aug 26, 2020 at 11:46
  • 2
    You treat num like a string but it is a number. Use const num = "1234" Commented Aug 26, 2020 at 11:46
  • Why? what is wrong with sort? Is just an excercise, or does it have a serious use case? Commented Aug 26, 2020 at 11:51
  • 1
    en.wikipedia.org/wiki/Bubble_sort Commented Aug 26, 2020 at 12:03

5 Answers 5

1

let num = 32145; // you can't change constants after declaration so we are using variables
num = num.toString(); // convert number to string
num = num.split(''); // split the number to array
//Bubble Sort starts here
var len = num.length;
for (var i = len - 1; i >= 0; i--) {
    for (var j = 1; j <= i; j++) {
        if (num[j - 1] > num[j]) {
            var temp = num[j - 1];
            num[j - 1] = num[j];
            num[j] = temp;
        }
    }
}
//Bubble Sort ends here
num = num.join(''); //convert array to string
num = parseInt(num); //convert string to number
console.log(num);

You can read more about these functions below

  1. Number to string
  2. String split
  3. Array join
  4. bubble sort function
  5. ParseInt
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the corrections, for the example and explanations, now it's clearer .. Thank you very much angel.bonev!
@BitterPirate you're welcome I've added some extra links if you want to learn more about these functions
@BitterPirate @angel.bonev One small edition I'd make is to simply print num.join(). The reason why is because if we have 0 somewhere in num, it'll get put to the start and parseInt() ignores numbers that have 0 at the start because numbers don't start with 0! ;)
1

Here is the working example without javascript sort:

let num = "12345"
 
for (let j = 0; j < num.length - 1; j++) {
    for (let i = 0; i < num.length - 1; i++) {
      if (num[i] < num[i + 1]) {
        let temp = num[i + 1];
        num = num.replace(num[i+1], num[i]);
        num = num.replace(num[i], temp);
      }; 
    }; 
};
 
console.log(num);

Comments

0

You can do this sorting like this It's much simpler

const test = "124536"
const result = test.split('').sort().join('');

const test = "124536"

const result = test.split('').sort().join('');

console.log(result)

2 Comments

OP specifically said they didn't want to use .sort()
thank jay, freefaller rights, without using sort but thank anyway..
0

You can hold your numbers in an array if you want.

    var numbers= [1,2,3,4,5];
    for(i=0;i<numbers.length-1;i++){
        for(j=0;j<numbers.length-i-1;j++){
            if(numbers[j]<numbers[j+1]){
                var temp = numbers[j];
                numbers[j] = numbers[j+1];
                numbers[j+1] = temp;
            }
        }
    }
    console.log(numbers);

Comments

0

Reason why your code didn't work

You thought that num.replace(...) would actually change num. In JavaScript, primitive data-types (of which numbers are one of) cannot be changed. What num.replace(...) actually does is return a completely new string that is identical to num - except, of course, with the replacement.

function showLowestToHighest(num) {
    let numAsString = num.toString();
    let rawNumArray = [];
    for (const character of numAsString) {
        rawNumArray.push(Number.parseInt(character));
    }
    let sortedNumArray = [];

    for (let index = 0; index < numAsString.length; index++) {
        let smallestNum = Math.min(...rawNumArray);
        sortedNumArray.push(smallestNum);
        let smallestNumIndex = rawNumArray.indexOf(smallestNum);
        rawNumArray.splice(smallestNumIndex, 1);
    }
    console.log(sortedNumArray.join(''));
}

showLowestToHighest(894560);

How this function works

We establish rawNumArray - an array of the digits we're looking at. We then remove the smallest digit from rawNumArray and place it at the end of sortedNumArray, doing this until rawNumArray is empty. Finally, we log out the contents of sortedNumArray - as a string.

Weakness: if the number if larger then Number.MAX_SAFE_INTEGER it won't work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.