问题描述
在花了几个小时试图解决 This Question 之后,我决定看看解决方案,但我似乎无法通过我厚厚的头骨获得解决方案的一部分。
解决方案:
const myGroupBy = (collection,q) => {
collection = Object.values(collection);
switch (typeof q) {
case "string":
return collection.reduce((a,c) => (a[c[q]] = [...(a[c[q]] || []),c],a),{});
case "function":
return collection.reduce((a,c) => (a[q(c)] = [...(a[q(c)] || []),{});
default:
const [[k,v]] = Object.entries(q);
return collection.reduce((a,c) => (a[c[k] === v] = [...(a[c[k] === v] || []),{});
}
};
我不明白的部分:(a[c[q]] = [...(a[c[q]] || []),a)
任何帮助将不胜感激。
解决方法
当数组可能尚不存在时,将新项添加到数组是一种难以理解的方式。
.reduce((a,c) => (a[c[q]] = [...(a[c[q]] || []),c],a),{});
是,未缩小:
.reduce((a,c) => {
const prop = c[q];
if (!a[prop]) {
// array doesn't exist yet; create it
a[prop] = [];
}
// it definitely exists now. Now,push the new item to it
a[prop].push(c);
// return the accumulator
return a;
},{});
此处的其他 .reduce
使用了相同的模式。
.reduce
可能在这里不太合适,但简单的循环会更有意义,因为累加器永远不会改变。
const obj = {};
for (const c of collection) {
const prop = c[q];
if (!obj[prop]) {
// array doesn't exist yet; create it
obj[prop] = [];
}
// it definitely exists now. Now,push the new item to it
obj[prop].push(c);
}
return obj;
这些方法确实改变了累加器上的现有数组,而不是重新分配全新的数组(就像您的原始代码所做的那样) - 但由于数组一开始是空的,它不会有任何影响(正面或负面)。>