Home > Blockchain >  How JS sorting the numbers?
How JS sorting the numbers?

Time:06-19

I'm learning Javascript and I faced a problem with sorting numbers I don't understand how work sorting function and I find an other way to sort the numbers but it was with list not with arrays I need explanations. I also see this link : Sorting array with numbers without sort() method

const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML = points;

points.sort(function(a, b) {
  return a - b
});
document.getElementById("demo2").innerHTML = points;

document.getElementById("demo3").innerHTML = points.sort();
unsorted:
<div id="demo1"></div>
sorted:
<div id="demo2"></div>
sorted alphabetically:
<div id="demo3"></div>

CodePudding user response:

const points = [40, 100, 1, 5, 25, 10];

console.log(points)

console.log(points.sort())

console.log(points.sort(function(a, b){return (a - b);}))

By default, the sort() function sorts values as strings.

However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce incorrect results when sorting numbers.

You can fix this by providing a compare function:

const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b});

Solution

CodePudding user response:

I am not sure about the question, but the sort of numbers, letters, and alph-numeric are different. I guessed about your question that you are looking at the different ways with which the sort function works.

If this is the case then you may also look at this answer:

Html:

 Numbers Unsorted:
 <div id="demo1"></div>
 <br />
 Sorted:
 <div id="demo2"></div>
 <br />
 Sorted Alphabetically:
 <div id="demo3"></div>
 <br />
 Capital and Small Leters Sort:
 <div id="demo4"></div>
 <br />
 Alpha Numeric Sort:
 <div id="demo5"></div>

JavaScript:

//Numbers Unsorted
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML = points;        
points.sort();

//Numbers Sorted
document.getElementById("demo2").innerHTML = points;

//Strings Sorted
const strng = ['Forty', 'Hundred', 'One', 'Five', 'Twenty Five', 'Ten'];
strng.sort();   
document.getElementById("demo3").innerHTML = strng;

//Capital and Small Leters
const capSmallLet = ['Forty', 'Hundred', 'one', 'Five', 'Twenty Five', 'Ten'];
capSmallLet.sort(); 
document.getElementById("demo4").innerHTML = capSmallLet;

//Alphanumeric Sort
const alhaNum = ['40', 'Hundred', 'one', '5', 'Twenty Five', 'Ten'];
alhaNum.sort();

I think this answer will also help you in understanding Unix/Linux directory system.

There was a problem with creating Snippet. Please check the answer at CodePen https://codepen.io/vaqar/pen/eYVoGqO

  • Related