uniq
优质
小牛编辑
131浏览
2023-12-01
Creates a new sequence with every unique element from this one appearing exactly once (i.e., with duplicates removed).
Signature
Sequence.uniq = function(keyFn) { /*...*/ }
Sequence.uniq = function uniq(keyFn) { return new UniqueSequence(this, keyFn); }
Name | Type(s) | Description |
---|---|---|
keyFn | Function? | An optional function to produce the key for each object. This key is then tested for uniqueness as opposed to the object reference. |
returns | Sequence | The new sequence. |
Examples
Lazy([1, 2, 2, 3, 3, 3]).uniq() // sequence: [1, 2, 3] Lazy([{ name: 'mike' }, { name: 'sarah' }, { name: 'mike' } ]).uniq('name') // sequence: [{ name: 'mike' }, { name: 'sarah' }]
Benchmarks
function randomOf(array) { return function() { return array[Math.floor(Math.random() * array.length)]; }; } var mostUnique = Lazy.generate(randomOf(_.range(100)), 100).toArray(), someUnique = Lazy.generate(randomOf(_.range(50)), 100).toArray(), mostDupes = Lazy.generate(randomOf(_.range(5)), 100).toArray(); Lazy(mostUnique).uniq().each(Lazy.noop) // lazy - mostly unique elements Lazy(someUnique).uniq().each(Lazy.noop) // lazy - some unique elements Lazy(mostDupes).uniq().each(Lazy.noop) // lazy - mostly duplicate elements _.each(_.uniq(mostUnique), _.noop) // lodash - mostly unique elements _.each(_.uniq(someUnique), _.noop) // lodash - some unique elements _.each(_.uniq(mostDupes), _.noop) // lodash - mostly duplicate elements
Implementation | mostly unique elements | some unique elements | mostly duplicate elements |
---|---|---|---|
lazy | |||
lodash |