Use reduction to reduce array

Use the shortcut to find the number of times the elements are in the array. An array can have arrays inside recursively.

var foo = [ 1, [2, 3, 4], 4, [5,6,7], 4 ]; 

bar(foo, 4) will return 3.

+5
source share
5 answers

Try using Array.prototype.reduce .

 var foo = [1, [2, 3, 4], 4, [5, 6, 7], 4]; function f(arr, item) { return arr.reduce(function (s, i) { if (Array.isArray(i)) return s+f(i, item); return s+(i==item?1:0); }, 0); } console.log(f(foo, 4)) 

The function f is a recursive function. We go through all the elements and reduce them to one number. The function will also be called in all internal arrays, and for elements without an array, we simply check them as equal to the required element.

+4
source

You can consider all elements as one call with Array.prototype.forEach()

The forEach() method executes the provided function once for an array element.

And check if the element is an array, then the function is called again with the array parameter.

 var foo = ["a", ["b", "c", "d"], "a"], object = {}; function count(a, o) { a.forEach(function (b) { if (Array.isArray(b)) { count(b, o); } else { o[b] = (o[b] || 0) + 1; } }) } count(foo, object); document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>'); 
+4
source

So, if you want recursion (and it will work in any browser):

 var foo = [ "a", ["b", "c", "d"], "a" ]; function bar(arr, item) { var count = 0; if (arr.length == 0) { return 0; } for (var i = 0, l = arr.length; i < l; i++) { var v = arr[i]; if (typeof v === "string") { if (v === item) { count++; } } else { count = count + bar(v, item); } } return count; } console.log(bar(foo, "a")); 
+2
source

Here is another functional type of interpretation that does not require an external state, although it would be more ineffective.

 var foo = [ "a", ["b", "c", "d"], ["a", "b"], "a" ]; function flatten( arr ){ return arr.reduce(function( ret, curr ){ return ret.concat( Array.isArray( curr ) ? flatten( curr ) : [ curr ] ); }, []); } function filterBy( arr, val ){ return arr.filter(function( item ){ return item === val; }) } console.log( flatten( foo ) ); console.log( filterBy( flatten( foo ), 'a') ); 
 <script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script> 
+2
source

Using underscore , you can count the number of occurrences of each element using this code:

 _.countBy(_.flatten(array), _.identity) 

Thus, the function foo can be implemented as follows:

 function bar(foo, element){ return _.countBy(_.flatten(foo), _.identity)[element]; } var foo = ["a", ["b", "c", "d"], "a"] console.log(bar(foo, "a")); 

Although this solution is not recursive, I should mention.

+1
source

Source: https://habr.com/ru/post/1239513/


All Articles