Skip to content

Commit

Permalink
Merging in jashkenas#194, adding an iterator to _.uniq
Browse files Browse the repository at this point in the history
  • Loading branch information
jashkenas committed Aug 3, 2011
2 parents 75b2195 + b930716 commit 03b341d
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
4 changes: 3 additions & 1 deletion index.html
Expand Up @@ -592,12 +592,14 @@ <h2>Array Functions</h2>
</pre>

<p id="uniq">
<b class="header">uniq</b><code>_.uniq(array, [isSorted])</code>
<b class="header">uniq</b><code>_.uniq(array, [isSorted], [iterator])</code>
<span class="alias">Alias: <b>unique</b></span>
<br />
Produces a duplicate-free version of the <b>array</b>, using <i>===</i> to test
object equality. If you know in advance that the <b>array</b> is sorted,
passing <i>true</i> for <b>isSorted</b> will run a much faster algorithm.
If you want to compute unique items based on a transformation, pass an
<b>iterator</b> function.
</p>
<pre>
_.uniq([1, 2, 1, 3, 1, 4]);
Expand Down
8 changes: 8 additions & 0 deletions test/arrays.js
Expand Up @@ -61,6 +61,14 @@ $(document).ready(function() {
var list = [1, 1, 1, 2, 2, 3];
equals(_.uniq(list, true).join(', '), '1, 2, 3', 'can find the unique values of a sorted array faster');

var list = [{name:'moe'}, {name:'curly'}, {name:'larry'}, {name:'curly'}];
var iterator = function(value) { return value.name; };
equals(_.map(_.uniq(list, false, iterator), iterator).join(', '), 'moe, curly, larry', 'can find the unique values of an array using a custom iterator');

var iterator = function(value) { return value +1; };
var list = [1, 2, 2, 3, 4, 4];
equals(_.uniq(list, true, iterator).join(', '), '1, 2, 3, 4', 'iterator works with sorted array');

var result = (function(){ return _.uniq(arguments); })(1, 2, 1, 3, 1, 4);
equals(result.join(', '), '1, 2, 3, 4', 'works on an arguments object');
});
Expand Down
12 changes: 9 additions & 3 deletions underscore.js
Expand Up @@ -333,11 +333,17 @@
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted) {
return _.reduce(array, function(memo, el, i) {
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el;
_.uniq = _.unique = function(array, isSorted, iterator) {
var initial = iterator ? _.map(array, iterator) : array;
var result = [];
_.reduce(initial, function(memo, el, i) {
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
memo[memo.length] = el;
result[result.length] = array[i];
}
return memo;
}, []);
return result;
};

// Produce an array that contains the union: each distinct element from all of
Expand Down

0 comments on commit 03b341d

Please sign in to comment.