pudaykiran pudaykiran - 10 days ago 5
Javascript Question

How to sort alphanumeric array in javascript

I had the problem of sorting alphanumeric array.

sort pattern number comes first then letter

09312d27-4ddc-458e-95dd-74531f787368,
1edcdde8-702e-4703-a505-ca81b77accdd,
.....


Code:

var alphaNumericArray = ['8a337e46-7d3f-46bc-b661-579f8d25fe09',
'09312d27-4ddc-458e-95dd-74531f787368',
'e7c5fba1-ce59-439a-a560-8f558e7c0ac4',
'1edcdde8-702e-4703-a505-ca81b77accdd',
'2f66ba6c-7fd2-4d52-8ed6-b0ee6d4d0310',
'7529217d-ee80-41eb-ade7-208674924ab9',
'523f4f75-8d0a-4ad1-8f40-e8bc679956be',
'80871291-c8de-47d9-9b02-3f8444c5d64e',
'7529217d-ee80-41eb-ade7-208674924ab9'];

alphaNumericArray.sort(function(a, b) {
a = a.value;
b = b.value;
return a-b;
});

//console.log(alphaNumericArray);
//alert(alphaNumericArray);


The output is not sorted. It shows me same array in alert popup and in console log.

Answer

var alphaNumericArray = [
  '8a337e46-7d3f-46bc-b661-579f8d25fe09',
  '09312d27-4ddc-458e-95dd-74531f787368',
  'e7c5fba1-ce59-439a-a560-8f558e7c0ac4',
  '1edcdde8-702e-4703-a505-ca81b77accdd',
  '2f66ba6c-7fd2-4d52-8ed6-b0ee6d4d0310',
  '7529217d-ee80-41eb-ade7-208674924ab9',
  '523f4f75-8d0a-4ad1-8f40-e8bc679956be',
  '80871291-c8de-47d9-9b02-3f8444c5d64e',
  '7529217d-ee80-41eb-ade7-208674924ab9'
];

alphaNumericArray.sort();

document.getElementById('out').textContent = JSON.stringify(alphaNumericArray, null, 2);
<pre id="out"></pre>

the result is:

[
  "09312d27-4ddc-458e-95dd-74531f787368",
  "1edcdde8-702e-4703-a505-ca81b77accdd",
  "2f66ba6c-7fd2-4d52-8ed6-b0ee6d4d0310",
  "523f4f75-8d0a-4ad1-8f40-e8bc679956be",
  "7529217d-ee80-41eb-ade7-208674924ab9",
  "7529217d-ee80-41eb-ade7-208674924ab9",
  "80871291-c8de-47d9-9b02-3f8444c5d64e",
  "8a337e46-7d3f-46bc-b661-579f8d25fe09",
  "e7c5fba1-ce59-439a-a560-8f558e7c0ac4"
]

read more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Comments