-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
array_search.js
48 lines (44 loc) · 1.43 KB
/
array_search.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
module.exports = function array_search(needle, haystack, argStrict) {
// discuss at: https://locutus.io/php/array_search/
// original by: Kevin van Zonneveld (https://kvz.io)
// input by: Brett Zamir (https://brett-zamir.me)
// bugfixed by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Reynier de la Rosa (https://scriptinside.blogspot.com.es/)
// test: skip-all
// example 1: array_search('zonneveld', {firstname: 'kevin', middle: 'van', surname: 'zonneveld'})
// returns 1: 'surname'
// example 2: array_search('3', {a: 3, b: 5, c: 7})
// returns 2: 'a'
const strict = !!argStrict
let key = ''
if (typeof needle === 'object' && needle.exec) {
// Duck-type for RegExp
if (!strict) {
// Let's consider case sensitive searches as strict
const flags =
'i' +
(needle.global ? 'g' : '') +
(needle.multiline ? 'm' : '') +
// sticky is FF only
(needle.sticky ? 'y' : '')
needle = new RegExp(needle.source, flags)
}
for (key in haystack) {
if (haystack.hasOwnProperty(key)) {
if (needle.test(haystack[key])) {
return key
}
}
}
return false
}
for (key in haystack) {
if (haystack.hasOwnProperty(key)) {
// eslint-disable-next-line eqeqeq
if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
return key
}
}
}
return false
}