I want to count only one type of product, which is the best way to do it, Example I want it to print the number of "ORANGE" = 2 and not the entire array:
var fruits = ["Banana", "Orange", "Apple", "Mango","Orange"];
fruits.length;
console.log(fruits.length);
Using
filter
:First you filter all the results that are
"Orange"
and then you print the length. Basically a sub-array of the original array is being created.Or with the new notation:
Update:
It occurs to me that to count the fruits the simplest thing is to create an object that stores the quantities:
On each pass of the iteration, the quantity
0
itself is initialized if that property does not exist in the object (usinghasOwnProperty
).You have to use a loop and a counter like this:
@alfredo's answer totally destroys the functional programming structure using avoid effects by mutating values outside the function, @César's answer is very good, it is the most common, you can also use an accumulator that counts on reduce.
In functional programming, recursion is not used, here is an example of how map works inside
As you can see, it returns an Array just like filter, that's why using .length with filter returns the count of the searched value.
I leave you this example with the map method