combine multiple arrays from array object and pick out uniques

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];
    })
}

1 answer

  • answered 2018-10-11 19:24 vizsatiz

    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 !!