13,044,705 members (65,845 online)
Rate this:
See more:
Hey friends i have an array with the following values

and i want to sort it in javascript in the following way in to three parts.

1) word starting from special character
2) word starting from digit
3) word starting from alphabets.

So this should be the sequence of the sorted array..

Posted 8-Jun-12 4:39am
Ravi Tuvar 8-Jun-12 10:40am

You can refer how in this page how the sorting is done..!

http://www.sciencebuddies.org/science-fair-projects/project_ideas/CompSci_p002.shtml
SAKryukov 8-Jun-12 11:15am

What character do you call "special"? There is no such thing.
What have you done? What's the problem?
--SA

Rate this:

## Solution 1

You can pass a sort function to JavaScript's array.sort().

```function sortFunction(a, b) {
// your array elements will be passed to this function as a, b
// TODO:
//   compare a to b
//   if a should come before b, return -1
//   if a should come after b, return 1
//   if a and b should be considered equal, return 0
return 0;
}

var myarray = ['asd', 'sdf', ..., '-sdf'];
myarray.sort(sortFunction);
```

Note: Searched Google for "javascript array sorting", found this[^] as the first result.
Rate this:

## Solution 2

```function MySort(alphabet)
{
return function(a, b) {
var index_a = alphabet.indexOf(a[0]),
index_b = alphabet.indexOf(b[0]);

if (index_a === index_b) {
// same first character, sort regular
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
} else {
return index_a - index_b;
}
}
}

sorter = MySort('*!@_.()#^&%-=+01234567989abcdefghijklmnopqrstuvwxyz');

console.log(items.sort(sorter));```

Top Experts
Last 24hrsThis month
 OriginalGriff 230 ppolymorphe 110 Sheila Pontes 75 Afzaal Ahmad Zeeshan 70 F-ES Sitecore 70
 OriginalGriff 4,485 RickZeeland 1,844 ppolymorphe 1,604 F-ES Sitecore 1,553 Dave Kreskowiak 1,349