HelloWorld
HelloWorld

Reputation: 111

How can I count strings in nested arrays?

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

Upvotes: 0

Views: 619

Answers (4)

r_batra
r_batra

Reputation: 410

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);

Upvotes: 0

Aziz.G
Aziz.G

Reputation: 3721

you can use flatMap

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


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

Upvotes: 1

Vishnu
Vishnu

Reputation: 897

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
  

Upvotes: 2

Paul
Paul

Reputation: 141829

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

Upvotes: 1

Related Questions