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());

 

//数组去重
let arr1 = [10,1,13,5,6,19,10,13];
let result = arr1.sort(compare).reduce((init, current)=>{
if(init.length===0 || init[init.length-1]!==current){//判断是否为第一个数值,或上个数值是否不等于当前数值
init.push(current);
}
return init;
}, []);
function compare(a,b){
return a-b;
}
console.log(result); //[1, 5, 6, 10, 13, 19]

转载于:https://www.cnblogs.com/jian138/p/8520189.html

你可能感兴趣的:(reduce的特殊用法)