4

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"]
0

2 Answers 2

7

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('');
Sign up to request clarification or add additional context in comments.

1 Comment

Makes sense! I had been using split -> sort -> join but was just trying to find a shorter method for code golf
3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.