你会如何减少这个数组? (阅读说明了解更多信息)
How would you reduce this array? (Read description for more info)
我脑子里乱七八糟的,可能是因为我在这个问题上纠结了一段时间。
我有一个数组(为了便于阅读而编辑):
variants = [
{title: 'color', children: [{title: 'red'}, {title: 'blue'}]
{title: 'size', children: [{title: 'large'}]
]
但需要如下输出:
variants = [
'color/red/size/large',
'color/blue/size/large',
]
或者如果初始数组是:
variants = [
{title: 'color', children: [{title: 'red'}, {title: 'blue'}]
{title: 'size', children: [{title: 'large'}, {title: 'medium'}]
]
新数组将是:
variants = [
'color/red/size/large',
'color/blue/size/large',
'color/red/size/medium',
'color/blue/size/medium',
]
这是一个相当简洁的 reduce,但它中间有一个嵌套的 flatMap(() => map())
调用,所以我不能保证它的效率。
const variants = [
{ title: 'color', children: [{ title: 'red' }, { title: 'blue' }] },
{ title: 'size', children: [{ title: 'large' }, { title: 'medium' }] },
]
variants.sort((a, b) => b.children.length - a.children.length);
const out = variants.reduce((acc, { title, children }) => {
const props = children.map(({ title: child }) => `${title}/${child}`);
acc = acc.length === 0 ? props : acc.flatMap(a => props.map(p => `${a}/${p}`));
return acc;
}, [])
console.log(out)
我脑子里乱七八糟的,可能是因为我在这个问题上纠结了一段时间。
我有一个数组(为了便于阅读而编辑):
variants = [
{title: 'color', children: [{title: 'red'}, {title: 'blue'}]
{title: 'size', children: [{title: 'large'}]
]
但需要如下输出:
variants = [
'color/red/size/large',
'color/blue/size/large',
]
或者如果初始数组是:
variants = [
{title: 'color', children: [{title: 'red'}, {title: 'blue'}]
{title: 'size', children: [{title: 'large'}, {title: 'medium'}]
]
新数组将是:
variants = [
'color/red/size/large',
'color/blue/size/large',
'color/red/size/medium',
'color/blue/size/medium',
]
这是一个相当简洁的 reduce,但它中间有一个嵌套的 flatMap(() => map())
调用,所以我不能保证它的效率。
const variants = [
{ title: 'color', children: [{ title: 'red' }, { title: 'blue' }] },
{ title: 'size', children: [{ title: 'large' }, { title: 'medium' }] },
]
variants.sort((a, b) => b.children.length - a.children.length);
const out = variants.reduce((acc, { title, children }) => {
const props = children.map(({ title: child }) => `${title}/${child}`);
acc = acc.length === 0 ? props : acc.flatMap(a => props.map(p => `${a}/${p}`));
return acc;
}, [])
console.log(out)