0

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 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

better way to do the sorting.
Edited the answer with Array.from(tags).sort()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.