Mapping and Reducing an Array within an Array of Objects in Javascript -
i'd appreciate advice on below. need extract keywords array within array of objects below, , reduce them show keywords without repetition.
my data json object below:
[ { "word":"cat", "answer":"a type of feline", "keywords": ["pet", "mouse-catcher"] }, { "word":"dog", "answer":"a type of canine", "keywords": ["pet", "cat-catcher"] }, ]
my js code below:
let keywordlist = data.map(entry => { let list = [...entry.keywords]; return ( list.reduce(( finalarray, current ) => finalarray.concat(current),[]) ); });
within react component, iterate on array using map again:
<p> keywords: {keywordlist.map((word, index) => { return ( <span key={word+index}> <a onclick={this.searchkeyword} href="#" id={word}>{word}</a> <span> | </span> </span> ); })} </p>
unfortunately, reduce function doesn't seem working, i'm getting array of arrays. advice great.
instead of map
, reduce
filter
:
var list = data.reduce((p, c) => { return p.concat(c.keywords.filter(el => !p.includes(el))); }, []);
Comments
Post a Comment