Skip to content

Instantly share code, notes, and snippets.

@mmloveaa
Last active April 7, 2016 08:04
Show Gist options
  • Save mmloveaa/99eecb9b8659d7c4cd1f7b2483c41231 to your computer and use it in GitHub Desktop.
Save mmloveaa/99eecb9b8659d7c4cd1f7b2483c41231 to your computer and use it in GitHub Desktop.
4-6 - Q25 Count String
Count Strings in Objects
Complete the function stringCount that will count all string values inside an object. The object will be filled with all kinds of data, including arrays and other objects. Your function must find all strings, which may be deeply nested.
Input Format:
The function will have one argument
obj - an object, which may contain all kinds of data.
Output Format:
The function will return a number, representing the number of strings in the object.
Sample Input 1:
{
"first": "1",
"second": "2",
"third": false,
"fourth": [
"anytime",
2,
3,
4
],
"fifth": null
}
Sample Output 1:
3
Explanation: The three strings are "1", "2", and "anytime".
Sample Input 2:
{
"a": [1, 2, "3", 4],
"b": {
"one": [true, false, "maybe"],
"two": {},
"three": [[[[[[""]]]]]]
},
"c": [
{
"d": [
{
"e": null,
"f": "ok"
}
]
}
]
}
Sample Output 2:
4
Explanation: The four strings are "3", "maybe", "", and "ok". (Note that the empty string is included in the count.)
function strCount(inp){
var strNum =0;
if(Array.isArray(inp)){
inp.forEach(function(val){
if(typeof val ==="string"){
strNum++;
}else{
strNum += strCount(val);
}
})
return strNum;
}
else if(typeof inp ==="object"){
for(var key in inp){
if(typeof inp[key]==="string"){
strNum++;
}
else{
strNum += strCount(inp[key]);
}
}
}
else if(typeof inp ==="string"){
strNum++;
}
return strNum;
}
var testStr = {
"a": [1, 2, "3", 4],
"b": {
"one": [true, false, "maybe"],
"two": {},
"three": [[[[[[""]]]]]]
},
"c": [
{
"d": [
{
"e": null,
"f": "ok"
}
]
}
]
}
strCount(testStr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment