SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Nov 2010
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to Sort this type of Array

    Hello,

    I'm writing a javascript program where I'm counting the number of occurrences of each character in a string.

    For example "hello world":

    charArray['h'] = 1;
    charArray['e'] = 1;
    charArray['l'] = 3;
    charArray['o'] = 2;
    charArray['w'] = 1;
    charArray['r'] = 1;
    charArray['d'] = 1;
    charArray[''] = 1;

    Is there a way to sort this array by the number values in descending order? Writing a custom sort() doesn't seem to work with string indexes. Perhaps I should store the information in a different format? Two-Dimensional array?

    Any help is greatly appreciated.

    Thanks.

  2. #2
    SitePoint Evangelist
    Join Date
    Jun 2007
    Location
    North Yorkshire, UK
    Posts
    483
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I would normally have a second array of the letters in you charArray for example


    indxCharArray[0] = 'h'
    indxCharArray[1] = 'e'
    indxCharArray[2] = 'l'
    indxCharArray[3] = 'o'
    indxCharArray[4] = 'w'
    indxCharArray[5] = 'o'
    indxCharArray[6] = 'r'
    indxCharArray[7] = 'd'
    indxCharArray[8] = ' '

    and then sort that array based on the value of charArray[indxCharArray[i]]

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is a bit much for 'hello world', I admit, but maybe you have longer strings.
    Code:
    function charcount(s, ci){
    	if(ci) s= s.toLowerCase();	// optional
    	s= s.replace(/[^a-zA-Z]+/g,''); // optional
    	var a= s.split('').sort(), b= [], tem, count;
    	while(a.length){
    		tem= a.shift();
    		count= 1;
    		while(a[0]== tem){
    			++count;
    			a.shift();
    		}
    		if(!b[count]) b[count]= [count];
    		b[count].push(tem);
    	}
    	for(var i= 0, L= b.length; i<L; i++){
    		tem= b[i];
    		if(tem) a.push(tem.shift()+': '+tem.join(', '));
    	}
    	return a.sort(function(a, b){
    		return parseInt(b)-parseInt(a);
    	});
    }
    Code:
    //test
    var s= "hello world";
    alert('Character count\n\t'+charcount(s, true).join('\n\t'))
    
    /*  returned value: 
    Character count
    	3: l
    	2: o
    	1: d, e, h, r, w
    */


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •