1

I'm trying to resolve this course but as a beginner in JavaScript, it's a little hard. this course is about sorting an array of numbers (sorry for my bad english it's not my first language )

i used the method .sort() cause the numbers are in an array but it keep telling me that it's not a fonction..

numbers = document.getElementById("numbers").value;

(function() { document.getElementById("run").addEventListener("click", function() {
    numbers.sort()
    alert(numbers);
  });
})();
<div class="field">
    <label for="numbers">Numbers:</label>
    <input type="text" name="numbers" id="numbers" readonly value="2, 4, 14, 10, 90, 23, 16" />
</div>
<div class="actions">
    <button type="button" id="run">Run</button>
</div>

when i run my code it says that numbers.sort() is not a fonction but how can i use this method ?? Thanks you in advance !

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
M.Ela
  • 81
  • 1
  • 7

2 Answers2

2

numbers is a string so you can't use sort on string directly. you need to change it to array. Here i am doing it using split function.

function handle() {
    let numbers = document.getElementById("numbers").value;
    numbers=numbers.split(',').sort((a,b)=>a-b)
    alert(numbers);
};
<div class="field">
<label for="numbers">Numbers:</label>
<input type="text" name="numbers" id="numbers" readonly value="2,4,14,10,90,23,16" />
</div>
<div class="actions">
<button type="button" id="run" onclick='handle()'>Run</button>
</div>
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

the input value is just a a long string. You need to split the string into an array of string representation of numbers, then convert them to number type. to use the compare function, you need to to provide a compare function, otherwise, the function sort by the unicode representation. Here is a working code:

function handle() {
    var numbersInputElemnt = document.querySelector('#numbers');
    var numbersStr = numbersInputElemnt.value;
    var numbers = numbersStr.split(', ').map(function(numStr) {
  return +numStr;
});
    numbers.sort(function compareNumbers(a, b) {
  return a - b;
});


    alert(numbers);
};
<div class="field">
    <label for="numbers">Numbers:</label>
    <input type="text" name="numbers" id="numbers" readonly value="2, 4, 14, 10, 90, 23, 16" />
</div>
<div class="actions">
      <button type="button" id="run" onclick="handle()">Run</button>
</div>
Itai
  • 387
  • 1
  • 7
  • 15