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

后端 未结 4 880
南笙
南笙 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 04:18

    I think this is a simple approach but you can get tangled with it:

     function countItems(arr, item, count = 0){
         if(!arr.length) return count; //if the array is empty then there's nothing else to count
         let cTemp;
         if(Array.isArray(arr[0])){ //if the next item is an array
             cTemp = countItems(arr[0], item); //count the items in that array
         } else {
             cTemp = arr[0] === item ? 1 : 0; //if it's a string the compare it with item
             //1 if we found it
             //0 if we didn't
         }
         return countItems(arr.slice(1), item, count+cTemp);
         //count the items of the rest of the array and add what we found
         //arr.slice(1) is the rest of the array
         //cTemp is the count for the first item in the array
     }
    

    Which of course can be rewritten into a single line:

     let countItems = ([first, ...rest], item, count = 0) => !first ? count : countItems(rest, item, count + (Array.isArray(first) ? countItems(first, item) : +(first === item)))
    

提交回复
热议问题