0

I was studying JS in CodeWars and I didn't find a method to remove all duplicated elements in an array. I need to do exactly this:

a = [1,2,2,2,3,4,5,6,6,7] b = [1,2,7,8,9]

Return a unique array = [3,4,5,8,9] delete all the duplicated items, including the first occurrence

How can I do this? I already use for, if, forEach, but no success.

  • Please visit [help], take [tour] to see what and [ask]. Do some research, ***[search for related topics on SO](https://www.google.com/search?q=merge+arrays+remove+duplicates+javascript+site:stackoverflow.com)***; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Sep 08 '21 at 16:53

1 Answers1

1

You may simply

  • count the occurences of each element (to preserve the original element types, you may apply Array.prototype.reduce() together with Map against merged array)
  • then, filter out those that are seen more than once:

const  a = [1,2,2,2,3,4,5,6,6,7],
       b = [1,2,7,8,9],
       
       uniques = [
         ...[...a, ...b]
          .reduce((acc,item) => 
            (acc.set(item, (acc.get(item)||0)+1), acc), new Map)
          .entries()
       ].reduce((acc, [key, value]) => 
        (value === 1 && acc.push(key), acc), [])
      
    
console.log(uniques)
.as-console-wrapper {min-height:100%}
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42