0

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 ?

5
  • Possible duplicate of How to merge two arrays in Javascript and de-duplicate items Commented Apr 24, 2017 at 8:06
  • 1
    Yeah, I read that topic... but there was known number of arrays. Thats the problem for me now. Cant understand how to loop through all (unknown number) arrays, which can be added by user: it may be two or much more. Commented Apr 24, 2017 at 8:09
  • The line in your loop is overwriting the previous arrayCommon, not adding to it. Commented Apr 24, 2017 at 8:10
  • @nnnnnn, yes, I see that. Any ideas how to avoid it? Commented Apr 24, 2017 at 8:11
  • Maybe you want an empty Set created before the loop, add to the set inside the loop, then convert set to array after the loop. Either that or just .concat() the individual arrays to form a master list with duplicates, then remove the duplicates from the full list. Commented Apr 24, 2017 at 8:12

1 Answer 1

2

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

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

2 Comments

@georg - Oh, of course. Answer updated. Thanks. (I'm still used to posting answers that don't use the new operators so that the code'll work in IE, but of course the other parts of the code already used ..., so...)
Yeah, thanks! Me too trying to get used to this features )

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.