NeedH8
NeedH8

Reputation: 482

Merging unknown number of arrays without duplicates

Can't understand how to loop through all arrays and push it into one avoiding duplicates, so I can have the result like:

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

So far, now I have the following, but it is not that expected:

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>

Can anyone help ?

Upvotes: 0

Views: 178

Answers (1)

nnnnnn
nnnnnn

Reputation: 150040

If you could convert your config to be an array of arrays then you could call .concat() with that to combine them into a single array with duplicates. Then use a Set to remove the duplicates after that:

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

Upvotes: 2

Related Questions