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

后端 未结 4 876
南笙
南笙 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:14

    You could take a recursive approach for arrays or check the value and add the result of the boolean value.

    function count(array, value) {
        return array.reduce((s, a) => s + (Array.isArray(a) ? count(a, value) : a === value), 0);
    }
    
    var array = ["apple", ["banana", "strawberry", "dsffsd", "apple"], "banana", ["sdfdsf", "apple", ["apple", ["nonapple", "apple", ["apple"]]]], "apple"];
    
    console.log(count(array, 'apple'));

    Version with a for loop.

    function count(array, value) {
        var i,
            sum = 0;
    
        for (i = 0; i < array.length; i++) {
            if (Array.isArray(array[i])) {
                sum += count(array[i], value);
                continue;
            }
            sum += array[i] === value;
        }
        return sum;
    }
    
    var array = ["apple", ["banana", "strawberry", "dsffsd", "apple"], "banana", ["sdfdsf", "apple", ["apple", ["nonapple", "apple", ["apple"]]]], "apple"];
    
    console.log(count(array, 'apple'));

提交回复
热议问题