合并未知数量的数组而不重复

时间:2017-04-24 08:04:43

标签: javascript arrays

无法理解如何遍历所有数组并将其推入一个避免重复的数组,因此我可以获得如下结果:

['All', 'Images', 'Video']

到目前为止,我现在有以下内容,但不是预期的那样:



let filterize = function(el, config){
	let target =  document.getElementById(el);
	let arrayCommon;
	for(let value in config) {		
		arrayCommon = [...new Set([...config[value].filter])];
	} 
	
	console.log(arrayCommon) 
	
	
}

var filterize_init = new filterize('Filtered', {
	element_1: {
		filter: ['All', 'Image']
	},
	element_2: {
		filter: ['All', 'Video']
	}
})

<div class="wrapper">
	<div id="Filtered" class="filter-content">
		
	</div>
</div>
&#13;
&#13;
&#13;

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

如果您可以将config转换为数组数组,那么您可以使用它来调用.concat()将它们组合成一个带有重复项的单个数组。然后使用Set删除重复项:

let filterize = function(el, config){
    let working = Object.keys(config).map(e => config[e].filter);
    let arrayCommon = [...new Set([].concat(...working))];

    console.log(arrayCommon);	
}

var filterize_init = new filterize('Filtered', {
	element_1: {
		filter: ['All', 'Image']
	},
	element_2: {
		filter: ['All', 'Video']
	},
	element_3: {
		filter: ['All', 'Whatever', 'Video', 'Image', 'Test']
	}
})