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 ma-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.
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 ma-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.
Share Improve this question asked Jul 31, 2016 at 7:07 gyorgybeczgyorgybecz 852 gold badges2 silver badges7 bronze badges 3-
chars.push()
pushes into an array, so a ma is expected - usechars +=
instead – StudioTime Commented Jul 31, 2016 at 7:09 -
Note that by default
.sort()
doesn't sort alphabetically, it sorts according to each character's Unicode code point value. Which ends up as alphabetical if you have all lowercase or all uppercase letters, but in your case you don't. (So"apple"
es after"Zebra"
, but before"zebra"
.) – nnnnnn Commented Jul 31, 2016 at 7:14 - possible duplicate of stackoverflow./questions/30912663/… – martinho Commented Mar 23, 2020 at 7:58
2 Answers
Reset to default 16join()
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('');
const sorted = str.split('').sort().join('')