最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Sorting a string alphabetically in Javascript - Stack Overflow

programmeradmin7浏览0评论

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 - use chars += 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
Add a ment  | 

2 Answers 2

Reset to default 16

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('')
发布评论

评论列表(0)

  1. 暂无评论