I have the following PHP-script, now I need to do the same thing in JavaScript. Is there a function in JavaScript that works similar to the PHP function, I have been searching for days but cannot find anything similar? What I want to do is to count the number of times a certain word is being used in an array.
$interfaceA = array($interfaceA_1,$interfaceA_2,$interfaceA_3,$interfaceA_4,$interfaceA_5,$interfaceA_6,$interfaceA_7,$interfaceA_8);
$interfaceA_array=array_count_values($interfaceA);
$knappsatsA = $interfaceA_array[gui_knappsats];
$touchpanelA = $interfaceA_array[gui_touchpanel];
Another elegant solution would be to use Array.prototype.reduce. Given:
You can just run reduce on it:
Finally you can check the result:
In the sample above reduce takes two parameters:
Whatever the function returns, it will be used as the accumulator value in the next call.
From a type perspective, whatever the type of the array elements, the type of the accumulator must match the type of the second argument of reduce (initial value), and the type of the return value of the anonymous function. This will also be the type of the return value of reduce.
Try
Why not simply create a new javascript array "counts" Iterate over original array, and increament the count of "counts" for keys encountered in the array. http://jsfiddle.net/4t28P/1/
How about this: