Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Javascript Sorting Sort
Hey friends i have an array with the following values
 
asd sdf dsdf 1sadf *sdf !sdf @asdf _asd .sadf (sadf )sadf #sadf ^asdf &asdf %asdf -sadf =sadf +sadf -sdf
 

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..
 
Please help me out..!
Posted 8-Jun-12 5:39am
Comments
Ravi Tuvar at 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 at 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: bad
good
Please Sign up or sign in to vote.

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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Here is the correct answer..!
 

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;
        }
    }
}
 
var items = ['asd','sdf', 'dsdf', '1sadf', '*sdf', '!sdf', '@asdf', '_asd', '.sadf', '(sadf', ')sadf', '#sadf', '^asdf', '&asdf', '%asdf', '-sadf', '=sadf', '+sadf', '-sdf', 'sef'],
sorter = MySort('*!@_.()#^&%-=+01234567989abcdefghijklmnopqrstuvwxyz');
 
console.log(items.sort(sorter));
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 245
1 Kamal Rocks 184
2 Sergey Alexandrovich Kryukov 175
3 BillWoodruff 173
4 PIEBALDconsult 160
0 OriginalGriff 5,655
1 DamithSL 4,506
2 Maciej Los 3,997
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,180


Advertise | Privacy | Mobile
Web03 | 2.8.141216.1 | Last Updated 11 Jun 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100