From b9307163b974991885b50e3ac09b54bd00a06153 Mon Sep 17 00:00:00 2001 From: Alfredo Mesen Date: Tue, 3 May 2011 21:09:54 -0600 Subject: [PATCH] Add optional iterator to _.uniq --- index.html | 6 +++++- test/arrays.js | 8 ++++++++ underscore.js | 12 +++++++++--- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/index.html b/index.html index 685706fee..db4de3758 100644 --- a/index.html +++ b/index.html @@ -547,16 +547,20 @@ _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);

- uniq_.uniq(array, [isSorted]) + uniq_.uniq(array, [isSorted], [iterator]) Alias: unique
Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. + Can receive an iterator to determine which part of the element gets tested.

 _.uniq([1, 2, 1, 3, 1, 4]);
 => [1, 2, 3, 4]
+
+_.uniq([{name:'moe'}, {name:'curly'}, {name:'larry'}, {name:'curly'}], false, function (value) { return value.name; })
+=>[{name:'moe'}, {name:'curly'}, {name:'larry'}]
 

diff --git a/test/arrays.js b/test/arrays.js index e031afe9b..985f4d956 100644 --- a/test/arrays.js +++ b/test/arrays.js @@ -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'); }); diff --git a/underscore.js b/underscore.js index eaba008c4..3d83511fc 100644 --- a/underscore.js +++ b/underscore.js @@ -323,11 +323,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 every item shared between all the