// 统计分类 简单数组
let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
let countName = names.reduce(function(allname, name) {
if (name in allname) {
allname[name] ++
} else {
allname[name] = 1
}
return allname
},{} )
console.log(countName, 11)
// 统计分类 对象数组,指定属性
let people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
return objectArray.reduce(function (prev, obj) {
let key = obj[property];
if (!prev[key]) {
prev[key] = [];
}
prev[key].push(obj);
return prev;
}, {});
}
let groupedPeople = groupBy(people, 'age');
console.log(groupedPeople, 22)
// 给 Array 绑定自定义属性
Array.prototype.average = function() {
let sum = this.reduce(function(prev, cur) {
return prev+cur
})
return sum / this.length
}
let arr = [1,2,3,4,5]
console.log(arr.average(), 33)
// 两层 reduce 分类
const arr2 = [
['lan','中文','english'],
['login','登录','Login'],
['register','注册','Register']]
// const i18nHandle = (arr) => {
// let obj = {en: {}, zh: {}}
const a = arr2.reduce((acc, [key, ...item]) => {
Object.keys(acc).forEach((cur, i) => {
acc[cur][key] = item[i]
})
return acc
}, {en: {}, zh: {}})
console.log(a)
const data = [
['language', 'zhongwen', 'english'],
['login', '登录', 'login'],
['logout', '退出', 'logout']
]
const keyMap = {
'zhongwen': 'zh',
'english': 'en',
}
const transformLanguage = (data, keyMap) => {
const [[_, ...originKeys]] = data
return originKeys.reduce((acc, originKey, index) => {
const key = keyMap[originKey]
acc[key] = data.reduce((acc, lineData) => {
acc[lineData[0]] = lineData[index]
return acc
}, {})
return acc
}, {})
}
console.log(transformLanguage(data, keyMap))
console