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.
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('');
const sorted = str.split('').sort().join('')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With