Search code examples
javascriptecmascript-6lodash

What's the most elegant way in ES6 to filter out duplicates in an array in Javascript


I've seen alot of answers to this topic but I'm not completely satisfied. The snippet I liked the most was this one:

[ ["1", "2"], ["1", "2", "3"], ["1", "2"] ]
  .filter(
    (path: string[], i: number, array: string[][]) => _.findIndex(array, x => _.isEqual(x, path)) === i
  )

This works but I find it waaaayy too verbose for my liking. Isn't there a more compact way to achieve this? Even if it means using lodash or something. I feel I'm missing something really obvious in the year 2019 (nearly 2020).


Solution

  • With lodash you can use _.uniqWith() to deduplicate the array, and use _.isEqual() as the comparator:

    const array = [["1", "2"], ["1", "2", "3"], ["1", "2"]]
    
    const result = _.uniqWith(array, _.isEqual)
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>