0

I want to list out my numbers in ascending order but run out with the odd numbers and continue with the even numbers, how can i solve it the answers should be 1, 2, 3, 4, 5, .... Here is my code:

var num = [1, 2, 70, 69, 80, 72, 93, 14, 85, 56, 14, 27, 12, 48];
var evennum = num.filter((n) => n % 2 == 0);
var oddnum = num.filter((n) => n % 2 == 1);

num.sort();
document.getElementById('numb').innerHTML = num;

oddnum.sort();
document.getElementById('odd').innerHTML = oddnum;

evennum.sort();
document.getElementById('even').innerHTML = evennum;
<p> Numbers: </p>
<p id="numb"></p>
<p> Odd Numbers: </p>
<p id="odd"></p>
<p> Even Numbers: </p>
<p id="even"></p>
DuDu
  • 59
  • 7
  • Use something like `oddnum.sort((a,b)=>a-b);` and the same for `evennum` – Nick May 28 '22 at 07:33
  • 1
    Please do not tag Javascript questions as `[java]`. They are completely different languages. – Stephen C May 28 '22 at 07:38
  • change the code from num.sort(); document.getElementById('numb').innerHTML = num; to num.sort(function(a,b){ return a-b; }); – DuDu May 29 '22 at 12:59
  • Read this article (just the Array sorting section): https://medium.com/@thesoggywaffle/7-common-bugs-in-typescript-and-javascript-5adbad7df5fb – Viraj Shah May 30 '22 at 01:21
  • Once you read the article linked above, you will realize that the default `Array.sort()` will sort elements alphabetically, unless you provide a comparison function. Which is why you need to use `Array.sort((a, b) => a - b)` – this tells JS to compare each element as numbers rather than strings. – Viraj Shah May 30 '22 at 01:22

0 Answers0