Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a string alphabetically in Javascript

I've some issues with a relativly simple task. I have to sort the characters of a string and return the sorted string (in Javascript). After googling for answers I figured out the solution but for some reason the methods doesn't return the output I expected.

var str = "Something";
var chars = [];

for (var i = 0; i < str.length; i++) {
    chars.push(str.charAt(i));
}

chars.sort().join("");
console.log(chars);

The output I receive is this:

["S", "e", "g", "h", "i", "m", "n", "o", "t"]

1.) Despite of using the .join() method the charachters are still comma-separated. Also tried to use the .replace() method but that brings me to the second issue.

2.) The typeof chars remains an object although .join() should return a string. I also tried using the .toString() method but the type of output still remains an object.

like image 320
gyorgybecz Avatar asked Dec 01 '22 16:12

gyorgybecz


2 Answers

join() does not modify the array, but returns a new object, which you currently not use. So your code should look like this:

var str = "Something";
var chars = [];

for (var i = 0; i < str.length; i++) {
    chars.push(str.charAt(i));
}

chars = chars.sort().join("");
console.log(chars);

You could, however, do this in a one liner:

let chars = str.split('').sort().join('');
like image 140
Sirko Avatar answered Dec 04 '22 13:12

Sirko


const sorted = str.split('').sort().join('')
like image 43
udnisap Avatar answered Dec 04 '22 12:12

udnisap