0

There is nested names array with only strings, need to loop through to find how many times each string appears. Since two elements have "bob" resulting function should return 2. How to search for the string even if array is nested?

var names = ["bob", ["steve", "michael", "bob", "chris"]];

function loop(){ 
    /* .... */
}

var result = loop(names, "bob");
console.log(result); // 2
2
  • You could either flatten the array or perhaps make use of recursion. Although can you clarify: "...since two elements have "bob"" - Are you trying to return the total number of "bob" strings, or the total number of elements that contain a "bob" string? Commented Jun 20, 2019 at 20:43
  • 1
    Loop through the array. If the element matches the string, add 1 to the counter. If the element is an array, recurse, and add the result to the counter. Finally, return the counter. Commented Jun 20, 2019 at 20:44

4 Answers 4

2

Example

var names = ["bob", ["steve", "michael", "bob", "chris"]];

function loop(names, searchString){ 
   var flattenArray = names.flat(Infinity);
   return flattenArray.filter(n => n === searchString).length;
}

var result = loop(names, "bob");
console.log(result); // 2
  

Sign up to request clarification or add additional context in comments.

1 Comment

While I don't think it detracts from the answer at all, it might be worth pointing out that .flat() is relatively new and not supported by all major browsers (Edge for example). If browser support is needed for Edge/IE, consider implementing a polyfill.
1

You can flatten and filter the array and then just return the length of the filtered array.

const names = ["bob", ["steve", "michael", "bob", "chris"]];

function loop ( arr, name ) {
  return arr.flat( Infinity ).filter( el => el === name ).length;
}

const result = loop(names, "bob");
console.log(result); // 2

Comments

1

you can use flatMap

var names = ["bob", ["steve", "michael", "bob", "chris"]];


console.log(names.flatMap(el => el === "bob").length)

Comments

0

You can simply iterate and determine this way as well:

var names = ["bob", ["steve", "michael", "bob", "chris"]];
var result = 0;
function loop(names,searchElement){ 
    for (var el=0;el<names.length;el++){
        if(Array.isArray(names[el])){
            for(var elem=0;elem<names[el].length;elem++){
                if(names[elem]==searchElement){
                    result = result + 1;
                }
            }
        }
        else{
            if(names[el]==searchElement){
                result = result + 1;
            }
        }
    }
    return result;
}

var results = loop(names, "bob");
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.