Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var baseCallback = require('../internal/baseCallback'),
2
baseUniq = require('../internal/baseUniq'),
3
isIterateeCall = require('../internal/isIterateeCall'),
4
sortedUniq = require('../internal/sortedUniq');
5
6
/**
7
* Creates a duplicate-free version of an array, using
8
* [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
9
* for equality comparisons, in which only the first occurence of each element
10
* is kept. Providing `true` for `isSorted` performs a faster search algorithm
11
* for sorted arrays. If an iteratee function is provided it is invoked for
12
* each element in the array to generate the criterion by which uniqueness
13
* is computed. The `iteratee` is bound to `thisArg` and invoked with three
14
* arguments: (value, index, array).
15
*
16
* If a property name is provided for `iteratee` the created `_.property`
17
* style callback returns the property value of the given element.
18
*
19
* If a value is also provided for `thisArg` the created `_.matchesProperty`
20
* style callback returns `true` for elements that have a matching property
21
* value, else `false`.
22
*
23
* If an object is provided for `iteratee` the created `_.matches` style
24
* callback returns `true` for elements that have the properties of the given
25
* object, else `false`.
26
*
27
* @static
28
* @memberOf _
29
* @alias unique
30
* @category Array
31
* @param {Array} array The array to inspect.
32
* @param {boolean} [isSorted] Specify the array is sorted.
33
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
34
* @param {*} [thisArg] The `this` binding of `iteratee`.
35
* @returns {Array} Returns the new duplicate-value-free array.
36
* @example
37
*
38
* _.uniq([2, 1, 2]);
39
* // => [2, 1]
40
*
41
* // using `isSorted`
42
* _.uniq([1, 1, 2], true);
43
* // => [1, 2]
44
*
45
* // using an iteratee function
46
* _.uniq([1, 2.5, 1.5, 2], function(n) {
47
* return this.floor(n);
48
* }, Math);
49
* // => [1, 2.5]
50
*
51
* // using the `_.property` callback shorthand
52
* _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
53
* // => [{ 'x': 1 }, { 'x': 2 }]
54
*/
55
function uniq(array, isSorted, iteratee, thisArg) {
56
var length = array ? array.length : 0;
57
if (!length) {
58
return [];
59
}
60
if (isSorted != null && typeof isSorted != 'boolean') {
61
thisArg = iteratee;
62
iteratee = isIterateeCall(array, isSorted, thisArg) ? null : isSorted;
63
isSorted = false;
64
}
65
iteratee = iteratee == null ? iteratee : baseCallback(iteratee, thisArg, 3);
66
return (isSorted)
67
? sortedUniq(array, iteratee)
68
: baseUniq(array, iteratee);
69
}
70
71
module.exports = uniq;
72
73