方法一:
function statisticalFieldNumber(arr) {
return arr.reduce(function (prev, next) {
prev[next] = (prev[next] + 1) || 1;
return prev;
}, {});
}
var arr = ["apple","orange","apple","orange","pear","orange","yellow"];
取指定字段个数: console.log(arr[‘apple’]) // 2
方法二:
var myArrays = new Array(1,4,5,1,41,4,1,54,123,1);
function countNum(arr,res) {
var newArrays = arr.filter(function(item){
return item == res;
});
return newArrays.length;
}
console.log("数组长度:" + myArrays.length);
console.log("原数组中1的个数:" + countNum(myArrays,1));
console.log("原数组中41的个数:" + countNum(myArrays,41));
console.log("原数组中123的个数:" + countNum(myArrays,123));
方法三:
function getWordCnt(arr){
var obj = {};
for(var i= 0, l = arr.length; i< l; i++){
var item = arr[i];
obj[item] = (obj[item] +1 ) || 1;
}
return obj;
}
console.log(getWordCnt(arr));//{apple: 2, orange: 3, pear: 1}