Reputation: 3040
The following code does what i want it to do. Which is to combine all of the unique tags
arrays from faqs[i].tags
... How can i re factor setFaqTopics()
with better javascript?
const faqs = [
{
tags: ['placing an order']
},{
tags: ['general']
},{
tags: ['placing an order']
},{
tags: ['general', 'dog']
}
]
function setFaqTopics(faqs) {
const tags = [];
let tag_arrs = faqs.map( it=> {
tags.push(it.tags[0])
if (it.tags[1]) tags.push(it.tags[1])
if (it.tags[2]) tags.push(it.tags[2])
if (it.tags[3]) tags.push(it.tags[3])
if (it.tags[4]) tags.push(it.tags[4])
if (it.tags[5]) tags.push(it.tags[5])
});
return uniq(tags);
}
console.log(setFaqTopics(faqs))
function uniq(a) {
return a.sort().filter(function(item, pos, ary) {
return !pos || item != ary[pos - 1];
})
}
Upvotes: 0
Views: 39
Reputation: 2163
I have added a better code below. Please take a look
const faqs = [
{
tags: ['placing an order']
},{
tags: ['general']
},{
tags: ['placing an order']
},{
tags: ['general', 'dog']
}
]
function setFaqTopics(faqs) {
const tags = new Set();
let tag_arrs = faqs.map( it => {
it.tags.map(val => {
tags.add(val)
});
});
return Arrays.from(tags).sort();
}
console.log(setFaqTopics(faqs))
Hope this helps !!
Upvotes: 3