javascriptstringsortingcharacterfromcharcode

console says cant read charCodeAt property


<script> 
var str=prompt('enter');
var a= str.split('');
for (j=0; j<str.length; j++){
for(i=j; i<str.length; i++)
{
  if(a[i].charCodeAt(0) > a[i+1].charCodeAt(0))
    {
      var b= a[i];
      a[i]=a[i+1];
      a[i+1]=b;
    }
}
}

     str=a.join('');
    document.write(str);

</script>

I know that sort method is more efficient but can somebody please tell whats wrong here. I want to sort the string but it shows cannt read charCodeAt property. Thank you;


Solution

  • You have out of bounds problem. It is happens when you try to compare charCodeAt of first character to second one, when second is doesn't exists (e.g. in the end of array you have no more chars to compare with).

    As we discussed in comments, you need just to sort your string by letters' charCodeAt, so you can use this code to sort your string:

    function bubbleSort(ar) {
      for (var i = (ar.length - 1); i >= 0; i--) {
        for (var j = 1; j <= i; j++) {
          if (ar[j-1] > ar[j]) {
            var temp = ar[j-1];
            ar[j-1] = ar[j];
            ar[j] = temp;
          }
        }
      }
      return ar;
    }
    
    function sortString(input) {
      return bubbleSort(
        input
          .split('')
          .map(function(char) {
            return char.charCodeAt(0)
          })
      ).map(function(charCode) {
        return String.fromCharCode(charCode);
      }).join('');
    }
    
    console.log(sortString('abcabcabc')); // => "aaabbbccc"
    console.log(sortString('вбавбавба')); // => "ааабббввв"

    Reference: https://www.cs.cmu.edu/~adamchik/15-121/lectures/Sorting%20Algorithms/sorting.html