从数组对象中组合多个数组并挑选出唯一性

时间:2018-10-11 19:06:38

标签: javascript arrays

以下代码可以实现我想要的功能。哪一个将tags中的所有唯一faqs[i].tags数组组合在一起...我该如何使用更好的JavaScript分解setFaqTopics()

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 个答案:

答案 0 :(得分:3)

我在下面添加了更好的代码。请看看

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

希望这会有所帮助!

相关问题