Back | Minified | Changelog

v1.1.2 was going to be a medium sized release and a few last minute changes went in, pushing the version to v1.1.3.


First new in this release is Array#findIndex. Consider the following examples:

['a','b','c'].indexOf('b'); ['a','b','c'].indexOf(function(el) { return el == 'b'; }); ['a','b','c'].indexOf(/b/);

In all 3 cases it should be obvious that we're looking for element "b" through various means, some of which may be required depending on the situation. However indexOf in the ES5 spec performs a simple === comparison operator on the elements. This means that example #2 would be looking for an anonymous function, and example #3 would be looking for an instance of a regex. Not what we were expecting. Array#findIndex allows discovery of the index through the standard find____ interface:

['a','b','c'].findIndex('b'); ['a','b','c'].findIndex(function(el) { return el == 'b'; }); ['a','b','c'].findIndex(/b/);

Arguments passed to iterating functions (when using one) are identical to indexOf: currentElement, currentIndex, and the array itself, in that order. Also like indexOf, -1 will be returned if no match is made, so this method can be swapped out and produce identical results.

Next up is Array#sample, which should be intuitive enough. It will sample any number of elements in the array randomly, and return a subset. If no argument is passed it will sample only a single element and return it directly:

['a','b','c'].sample(); > 'c' (randomly chosen) ['a','b','c'].sample(2); > ['c','a'] (randomly chosen)

Note that elements will not be chosen twice. That means that it will exhaust all elements in the array, which also means that any number larger than the array itself will be limited to the number of elements in the array.

Comparison of primitive types

Also added were 3 new methods that are similar, Number#compare, String#compare, and Date#compare. This methods are intended to allow complex sorting when the exact type isn't known. Consider this example:

array.sort(function(a, b) { return a - b; });

Although this is the standard way to sort a numeric array, 'a' - 'b' will produce NaN, so this method cannot be used on strings. The compare method, however, will run the correct comparison operation for that type. In the case of Number, it will run a - b, for String it will produce -1 if a b, and 0 if a == b. Dates will similarly do a straight comparison so they will be sorted properly as well. This way arrays of any type can use the exact same sort method:

array.sort(function(a, b) { return a.compare(b); });

What is nice about using similarly named methods is that compare methods can then be defined for instances of custom classes, so they can be properly compared as well. Array#sortBy now uses these compare methods internally if they exist, so sortBy will get also be able to leverage this advantage.