0

I'm working on a quick little exercise, and I am trying to allow a user to input 5 random numbers and have my script arrange them in ascending order, however it only works on single digit numbers. For example, when a user inputs 27, the program sorts it as if it were simply a 2. I am not certain what is causing this to happen, and I am open to any suggestions. (Also, code is not as concise as possible but please overlook)

let array = [];
let scrapArray = [];
array[0] = prompt("Please input a random number");
array[1] = prompt("Please input another random number");
array[2] = prompt("Please input another random number");
array[3] = prompt("Please input another random number");
array[4] = prompt("Please input another random number");
for (let i = 0; i < 5; i++) {
  for (let j = (i + 1); j < 5; j++) {
    if (array[i] >= array[j]) {
      scrapArray[i] = array[i];
      array[i] = array[j];
      array[j] = scrapArray[i]
    }
  }
}
console.log("the order of numbers from lowest to highest is: ");
for (let m = 0; m < array.length; m++) {
  console.log(array[m]);
}

1
  • You code has no problem and runs well on my computer. Could you run it on other computer? Commented Mar 16, 2020 at 3:08

1 Answer 1

1

You are inserting strings to array, not numbers. The type of the returned value of prompt() is string.

Convert the input to a number.

  array[0]=Number(prompt("Please input a random number"));
  array[1]=Number(prompt("Please input another random number"));
  array[2]=Number(prompt("Please input another random number"));
  array[3]=Number(prompt("Please input another random number"));
  array[4]=Number(prompt("Please input another random number"));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

Sign up to request clarification or add additional context in comments.

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.