Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var baseIndexOf = require('../internal/baseIndexOf'),
2
binaryIndex = require('../internal/binaryIndex');
3
4
/* Native method references for those with the same name as other `lodash` methods. */
5
var nativeMax = Math.max;
6
7
/**
8
* Gets the index at which the first occurrence of `value` is found in `array`
9
* using [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
10
* for equality comparisons. If `fromIndex` is negative, it is used as the offset
11
* from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
12
* performs a faster binary search.
13
*
14
* @static
15
* @memberOf _
16
* @category Array
17
* @param {Array} array The array to search.
18
* @param {*} value The value to search for.
19
* @param {boolean|number} [fromIndex=0] The index to search from or `true`
20
* to perform a binary search on a sorted array.
21
* @returns {number} Returns the index of the matched value, else `-1`.
22
* @example
23
*
24
* _.indexOf([1, 2, 1, 2], 2);
25
* // => 1
26
*
27
* // using `fromIndex`
28
* _.indexOf([1, 2, 1, 2], 2, 2);
29
* // => 3
30
*
31
* // performing a binary search
32
* _.indexOf([1, 1, 2, 2], 2, true);
33
* // => 2
34
*/
35
function indexOf(array, value, fromIndex) {
36
var length = array ? array.length : 0;
37
if (!length) {
38
return -1;
39
}
40
if (typeof fromIndex == 'number') {
41
fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
42
} else if (fromIndex) {
43
var index = binaryIndex(array, value),
44
other = array[index];
45
46
if (value === value ? (value === other) : (other !== other)) {
47
return index;
48
}
49
return -1;
50
}
51
return baseIndexOf(array, value, fromIndex || 0);
52
}
53
54
module.exports = indexOf;
55
56