Last active
May 17, 2016 03:10
-
-
Save daniellizik/98caaac222af0028063c53cda4705fb8 to your computer and use it in GitHub Desktop.
deep search, pull all matches
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function deepsearch_pull_matches(needle, haystack, parent, bucket = []) { | |
let i = 0; | |
let p; | |
let found; | |
if (Object.prototype.toString.call(haystack) === '[object Array]') { | |
for (i; i < haystack.length; i++) { | |
found = ds(needle, haystack[i], haystack, bucket); | |
if (found !== undefined && found !== bucket) | |
bucket.push(found); | |
} | |
} | |
else if (Object.prototype.toString.call(haystack) === '[object Object]') { | |
for (p in haystack) { | |
found = ds(needle, haystack[p], haystack, bucket); | |
if (found !== undefined && found !== bucket) | |
bucket.push(found); | |
} | |
} | |
else if (needle === haystack) { | |
return parent; | |
} | |
return bucket; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fixture = { | |
a: { | |
b: { | |
c: { | |
d: 'cat' | |
} | |
}, | |
e: [1, 2, 3, 4, { | |
a: { | |
h: 'mouse', | |
b: { | |
c: { | |
d: 'dog' | |
}, | |
e: [ | |
1, | |
2, | |
3, | |
56, | |
{ | |
f: { | |
g: { | |
wf: 'mouse' | |
} | |
} | |
} | |
] | |
} | |
} | |
}] | |
} | |
}; | |
var result = deepsearch_pull_matches('mouse', fixture); | |
console.log(Array.isArray(result), 'result should return array'); | |
console.log(result.length === 2, 'result should have two objects'); | |
console.log(result[0].hasOwnProperty('h'), 'result[0] should have h key and mouse value'); | |
console.log(result[1].hasOwnProperty('wf'), 'result[1] should have wf key and mouse value'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment