Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

javascript - How would you reduce this array? (Read description for more info)

My mind is boggled, maybe because i've been stuck on this issue for a bit.

I have an array (redacted for readability):

variants = [
 {title: 'color', children: [{title: 'red'}, {title: 'blue'}]
 {title: 'size', children: [{title: 'large'}] 
]

But need the following output:

variants = [ 
 'color/red/size/large',
 'color/blue/size/large',

]

or if the initial array is:

variants = [
 {title: 'color', children: [{title: 'red'}, {title: 'blue'}]
 {title: 'size', children: [{title: 'large'}, {title: 'medium'}] 
]

the new array would be:

variants = [ 
 'color/red/size/large',
 'color/blue/size/large',
 'color/red/size/medium',
 'color/blue/size/medium',
]
question from:https://stackoverflow.com/questions/65865752/how-would-you-reduce-this-array-read-description-for-more-info

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a fairly succinct reduce, but it has a nested flatMap(() => map()) call in its midst so I can't vouch for its efficiency.

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...