0
var temp=["dy34","fd","FD","av","AV","12esu",1,"DY34",1011,123,101];

When i sort the array i am getting this as:

result = [1,101,123,1011,"12esu","AV","av","dy34","DY34","FD","fd"]

but i need the result as like this:

result = [1,101,123,1011,"12esu","AV","av","DY34","dy34","FD","fd"]
  • 1
    How do you sort it? Default sort is: `["12esu", "AV", "DY34", "FD", "av", "dy34", "fd"]` – Andreas Louv May 25 '16 at 12:13
  • 2
    Well, what research have you done? What have you tried? You can't swing a dead cat here in the [tag:javascript] tag on SO without seeing examples of how to sort arrays. – T.J. Crowder May 25 '16 at 12:14
  • Please, read [this (how to ask)](http://stackoverflow.com/help/how-to-ask) and [this (mcve)](http://stackoverflow.com/help/mcve) before asking, as those will help you get more and better answers from the community.... @T.J.Crowder Well, you cant swing a dead cat anywhere.... – Bonatti May 25 '16 at 12:16
  • 1
    Where would you expect "AVE" to show up? – T.J. Crowder May 25 '16 at 12:43
  • 1
    So you've come back and edited the question, but chosen to just ignore the question above, which is necessary to answering your question? ***sigh*** – T.J. Crowder May 25 '16 at 13:11

1 Answers1

2

It seems you want to

  1. Compare array items in a numerical form
  2. If these are equal, compare them in a stringified case-insensitive form
  3. If these are also equal, compare the original forms.

/* isNumeric function taken from http://stackoverflow.com/a/1830844/1529630 */
var isNumeric = n => !isNaN(parseFloat(n)) && isFinite(n),
    numberForm = val => isNumeric(val) ? Number(val) : Infinity,
    iStringForm = val => String(val).toUpperCase();

var temp = ["dy34","fd","FD","av","AV","12esu",1,"DY34",1011,123,101];
for (var i = 0; i < temp.length; ++i)
  temp[i] = [numberForm(temp[i]), iStringForm(temp[i]), temp[i]];
temp.sort(function(a, b) {
  for (var i = 0; i < 3; ++i) {
    if (a[i] < b[i]) return -1;
    if (a[i] > b[i]) return +1;
  }
  return 0;
});
for (var i = 0; i < temp.length; ++i)
  temp[i] = temp[i][2];

console.log(temp);
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 1
    Possibly, the question is unclear. For instance, should "AVE" be *before* or *after* "av"? It doesn't tell us. With your code it would appear after (..."AV", "av", "AVE"...) which seems bizarre to me, but again, we just don't know. – T.J. Crowder May 25 '16 at 12:46