google/closure-library — pull request #310 by pauldraper (2014-07-05 18:33:53+00:00)
Title: Add goog.array.sortBy

This is similar to Python's [`sorted`](https://docs.python.org/3/library/functions.html#sorted) or Scala's [`sortBy`](http://www.scala-lang.org/api/2.10.3/index.html#scala.collection.SeqLike).

The motivation is making some types of sorting better by improving clarity and performance.

For example, the former ways of sorting strings case-insensitively were:

```
goog.array.sort(array, goog.string.caseInsensitiveCompare)
```
which sacrifices performance by calling `String(str).toLowerCase()` twice for every comparison. (In practice, `toLowerCase` is very fast for strings of reasonable length, but you could imagine a more involved calculation.)

Or,
```
var objects = goog.array.map(array, function(str, i) {
return {'key':str.toLowerCase(), 'value':i};
});
goog.array.sortObjectsByKey(objects, 'key');

var tmp = goog.array.clone(arr);
goog.array.forEach(objects, function(obj, i) {
arr[i] = tmp[obj['value']];
});
```
which sacrifices clarity. (This last example could be made a bit more intuitive by by not requiring an in-place sort, but it's still messy.)

This change allows callers to simply use

```
goog.array.sortBy(array, function(str) {
return str.toLowerCase();
});
```

---

I was not sure whether `goog.array.sortBy` or `goog.array.sortByKey` would be more clear. The second, for better or worse, resembles `goog.array.sortObjectsByKey`. I thought that they "key" might confuse callers with thinking of actual Javascript keys, objects, etc. (which are not visible to them), so I went with `sortBy`, but I have no strong feelings on the matter.