counting how many times an item appears in a multidimensional array in javascript

后端 未结 4 925
南笙
南笙 2021-01-27 03:35

Given a multidimensional array like this:

 var arr = [
\"apple\",
[\"banana\", \"strawberry\",\"dsffsd\", \"apple\"],
\"banana\",
[\"sdfdsf\",\"apple\",[\"apple\         


        
4条回答
  •  自闭症患者
    2021-01-27 03:57

    i think if you continue to return the count value and use it in your calculation you will be able to to get a final number without an outside variable:

    function countItems(arr, item) {
      let totc = 0; // totc is now local
      for (let i = 0; i < arr.length; i++ ){ // iterate on arr
            let isarray = arr[i].constructor === Array; // if the element is a nested array
            if(isarray){  totc += countItems(arr[i], item) } // recursion, using the return value
    
    
    
            let isin = arr[i] === item; // ELSE if the item is in the arr
            if(isin) { totc ++;  };
    
    
    
        }
        return totc; // the length of the sum array show how many items founded
      }
    }
    

    note that the only changes i made were to instantiate totc inside the function and to take the result of recursive calls and add them to the local total.

    Nina's answer is more elegant, but perhaps this will be easier to understand.

提交回复
热议问题