Return to Snippet

Revision: 27651
at December 5, 2010 10:16 by fengelz


Updated Code
var arr = ["Anne", "Carl", "Benny"];

arr.sort(desc); //returns "Carl","Benny","Anne"
arr.sort(asc); //returns "Anne","Benny","Carl"
alert(arr);

function desc(a, b)
{
  if(a.toLowerCase() > b.toLowerCase()){return -1;}
  else {return 1;}
}

function asc(a, b)
{
  if(a.toLowerCase() < b.toLowerCase()){return -1;}
  else {return 1;}
}

Revision: 27650
at June 18, 2010 22:37 by fengelz


Initial Code
var arr = ["Anne", "Carl", "Benny"];

arr.sort(desc); //returns "Carl","Benny","Anne"
arr.sort(asc); //returns "Anne","Benny","Carl"
alert(arr);

function desc(a, b)
{
  if(a.toLowerCase() > b.toLowerCase()){return -1;}
  else {return 1;}
}

function asc(a, b)
{
  if(a.toLowerCase() < b.toLowerCase()){return -1;}
  else {return 1;}
}

​

Initial URL

                                

Initial Description
If you need to sort an array in javascript this is how it should be done. Casting  toLowerCase() is optional but but necessary if fx "Anne" was spelled "anne"

Initial Title
sorting an array in javascript

Initial Tags
javascript, array

Initial Language
JavaScript