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 ?

NeedHate
  • 449
  • 5
  • 21
  • Possible duplicate of [How to merge two arrays in Javascript and de-duplicate items](http://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – George Apr 24 '17 at 08:06
  • 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. – NeedHate Apr 24 '17 at 08:09
  • The line in your loop is overwriting the previous arrayCommon, not adding to it. – nnnnnn Apr 24 '17 at 08:10
  • @nnnnnn, yes, I see that. Any ideas how to avoid it? – NeedHate Apr 24 '17 at 08: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. – nnnnnn Apr 24 '17 at 08:12

1 Answers1

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']
 }
})
nnnnnn
  • 138,378
  • 23
  • 180
  • 229
  • 1
    @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...) – nnnnnn Apr 24 '17 at 08:25
  • Yeah, thanks! Me too trying to get used to this features ) – NeedHate Apr 24 '17 at 08:28