Javascript:
function array_count_values( array ) { // Counts all the values of an array
//
// + original by: Ates Goral (http://magnetiq.com)
// + namespaced by: Michael White (http://crestidg.com)
var tmp_ar = new Object(), key;
var countValue = function (value) {
switch (typeof(value)) {
case "number":
if (Math.floor(value) != value) {
return;
}
case "string":
if (value in this) {
++this[value];
} else {
this[value] = 1;
}
}
}
if (array instanceof Array) {
array.forEach(countValue, tmp_ar);
} else if (array instanceof Object) {
for (var key in array) {
countValue.call(tmp_ar, array[key]);
}
}
return tmp_ar;
}
Примеры:
array_count_values([ 3, 5, 3, "foo", "bar", "foo" ]);
{3:2, 5:1, "foo":2, "bar":1}
array_count_values({ p1: 3, p2: 5, p3: 3, p4: "foo", p5: "bar", p6: "foo" });
{3:2, 5:1, "foo":2, "bar":1}
array_count_values([ true, 4.2, 42, "fubar" ]);
{42:1, "fubar":1}
|