Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.sort on a string

Tags:

javascript

Does anyone know why it's illegal to call Array.sort on a string?

[].sort.call("some string")
// "illegal access"

But calling Array.map, Array.reduce, or Array.filter is okay?

[].map.call("some string", function(x){ 
    return String.fromCharCode(x.charCodeAt(0)+1); 
});
// ["t", "p", "n", "f", "!", "t", "u", "s", "j", "o", "h"]

[].reduce.call("some string", function(a, b){ 
    return (+a === a ? a : a.charCodeAt(0)) + b.charCodeAt(0);
})
// 1131

[].filter.call("some string", function(x){ 
    return x.charCodeAt(0) > 110; 
})
// ["s", "o", "s", "t", "r"]
like image 389
nderscore Avatar asked Dec 26 '22 23:12

nderscore


2 Answers

Strings are immutable. You can't actually change a string; in particular, Array.prototype.sort would modify a string to be sorted, so you can't do that. You can only create a new, different string.

x = 'dcba';
// Create a character array from the string, sort that, then
// stick it back together.
y = x.split('').sort().join('');
like image 183
user2357112 supports Monica Avatar answered Dec 28 '22 14:12

user2357112 supports Monica


Because strings are immutable.

The functions you mention that work return a new object, they don't update the string in place.

Of course it's easy to sort a string a little less directly:

var sorted = "some string".split("").sort().join("");
like image 29
nnnnnn Avatar answered Dec 28 '22 12:12

nnnnnn