-1

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).

XDS
  • 3,786
  • 2
  • 36
  • 56
  • Questions asking us to suggest, find or recommend a book, tool, software library, plug-in, tutorial, explain a technique or provide any other off-site resource are off-topic for Stack Overflow – Jamie Nov 26 '19 at 09:45
  • Dup of https://stackoverflow.com/questions/44014799/javascript-how-to-remove-duplicate-arrays-inside-array-of-arrays – Salman A Nov 26 '19 at 10:14
  • Based on the accepted answer looks like it is a not-RTFM problem. – Salman A Nov 26 '19 at 10:33
  • I (like many others) looked into lodash documentation but somehow we couldn't find .uniqWith(). Sorry we are not as perfect as you are. – XDS Nov 26 '19 at 10:40

3 Answers3

1

You could take a bunch of closures and check with a Set and a stringified value.

var array = [["1", "2"], ["1", "2", "3"], ["1", "2"]],
    unique = array.filter(
        (s => a => 
            (j => !s.has(j) && s.add(j))
            (JSON.stringify(a))
        )
        (new Set)    
    );

console.log(unique);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
-1

Many ways actually, try to play in browser console. I usually using most straightforward with primitives:

const uniques = [...new Set(originalArray)]

For objects harder:

const uniques = original.reduce((result, object) => {
  if (!result.find((o) => i._id === object._id)) {
    result.push(object);
  }
  return result;
}, [])
Ivan Cherviakov
  • 528
  • 2
  • 12