数组分组:
含义: 数据按照某个特性归类
1. reduce+fn(cur, index)作为对象的key,值为按照fn筛选出来的数据
// 利用reduce分组
function group(arr, fn) {
// 不是数组
if (!Array.isArray(arr)) {
return arr
}
// 不是函数
if (typeof fn !== 'function') {
throw new TypeError('fn必须是一个函数')
}
var v
return arr.reduce((obj, cur, index) => {
v = fn(cur, index)
if (!Reflect.hasOwnProperty.call(obj, v)) {
obj[v] = []
}
obj[v].push(cur)
return obj
}, {})
}
// 按照字符串长度分组
let products = ["apple", "pear", "orange", "peach"];
const f1 = v => v.length
console.log(
group(products, f1),
);
// 按照分数分组
result = [{
name: "tom",
score: 60
}, {
name: "Jim",
score: 40
}, {
name: "Nick",
score: 88
}]
const fn = v => v.score >= 60
console.log(
group(result, fn),
);
2.filter+fn(value, index)作为对象的key,值为按照fn筛选出来的数据
// 利用forEach和filter分组
function group(arr, fn) {
// 不是数组
if (!Array.isArray(arr)) {
return arr
}
// 不是函数
if (typeof fn !== 'function') {
throw new TypeError('fn必须是一个函数')
}
let obj = {}
arr.forEach((item, key) => {
const v = fn(item, key)
obj[v] = arr.filter((ee, ix) => fn(ee, ix) === v)
});
return obj
}
// 按照字符串长度分组
let products = ["apple", "pear", "orange", "peach"];
const f1 = v => v.length
console.log(
group(products, f1),
);
// 按照分数分组
result = [{
name: "tom",
score: 60
}, {
name: "Jim",
score: 40
}, {
name: "Nick",
score: 88
}]
const fn = v => v.score >= 60
console.log(
group(result, fn),
);