// reduce()函数的应用 var people = [{ name: ‘Alice‘, age: 21 }, { name: ‘Max‘, age: 20 }, { name: ‘Jane‘, age: 20 }, { name: ‘Jane‘, age: 47 }, { name: ‘li‘, age: 20 }, { name: ‘wang‘, age: 18 }, { name: ‘wang‘, age: 20 }, ]; // 根据数组对象中的某一属性分组 var gg = people.reduce((calc, item) => { if (!calc[item.age]) { calc[item.age] = []; } calc[item.age].push(item) return calc }, {}) console.log(‘11111111111‘, gg) // 数组对象去重 var hash={}; var p = people.reduce((calc,item) => { if(!hash[item[‘name‘]]){ hash[item[‘name‘]] = true; calc.push(item) } return calc; },[]) console.log(‘数组对象去重‘,p)
// 封装数组对象根据某一属性分类的方法 function sortMyarr(arr,proper){ return arr.reduce((calc,currentitem) => { // var key = currentitem[proper]; var key = currentitem[proper]; if(!calc[key]){ calc[key] = []; } calc[key].push(currentitem) return calc; },{}) } console.log(‘分类封装‘,sortMyarr(people,‘name‘))