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"]
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('');
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("");
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