js根据需要计算数组中重复出现某个元素的个数

一、有时候的根据需要需要计算数组中某个元素重复出现的个数

var arr = ["apple","orange","apple","orange","pear","orange"];

计算出来重复出现的元素个数:{apple: 2, orange: 3, pear: 1}

二、代码实现

//统计一个数组中有多少个不重复的单词:

// 不用reduce时:

var arr = ["apple","orange","apple","orange","pear","orange"];

function getWordCnt(){

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());//{apple: 2, orange: 3, pear: 1}

// 用reduce时:

var arr = ["apple","orange","apple","orange","pear","orange"];

function getWordCnt(){

return arr.reduce(function(prev,next){

prev[next] = (prev[next] + 1) || 1;

return prev;

},{});

}

console.log(getWordCnt());//{apple: 2, orange: 3, pear: 1}

补充知识点:

若查询对象中某个属性没有,可自行为其添加

var muziObj = {};

muziObj['name'] = 'muzidigbig';

muziObj.age = 21;

console.log(muziObj)//{name: "muzidigbig", age: 21}

若有不足请多多指教!希望给您带来帮助!

总结

以上是 js根据需要计算数组中重复出现某个元素的个数 的全部内容, 来源链接: utcz.com/z/318754.html

回到顶部