2

This is how I would filter an array of numbers to become unique:

const unique = (value, index, self) => {
  return self.indexOf(value) === index
}

const costs = [10, 8, 5, 5, 8, 7]
const uniqueCosts = costs.filter(unique)

console.log(uniqueCosts) // [10,8,5,7]

How could I filter an array of arrays to be unique:
arr = [[10,10],[8,8],[5,5],[5,5],[8,8],[7,7]]
-> uniqueArr =[[10,10],[8,8],[5,5],[7,7]]

I have looked into creating a new Set() which again works quite well in a simple array however the .add function of a set seems to add an array to the set even if the array is already in the set.

Any help would be appreciated, I'm looking for a simple solution, using the power of existing functions in JavaScript without involving for/while loops.

Many thanks!

5
  • you can use .flat to flatten it and then use the same Commented Aug 11, 2020 at 17:01
  • 1
    Depends on what kind of uniqueness you want. Please show the expected output. I assume you're checking array equality, yes? Commented Aug 11, 2020 at 17:02
  • 4
    What is the expected result for arr = [[10,10],[8,8],[5,5],[5,5],[8,8],[7,7]]? Commented Aug 11, 2020 at 17:05
  • 1
    @ggorlen, @hev1 this is the expected result uniqueArr =[[10,10],[8,8],[5,5],[7,7]] Commented Aug 11, 2020 at 17:37
  • 1
    @HarmandeepSinghKalsi thank you, but I want to keep the structure of the embedded arrays however flat would lose that right? Commented Aug 11, 2020 at 17:39

1 Answer 1

2

You could take a Set with a serializing function for getting strings without different object references.

const
    serialize = v => JSON.stringify(v),
    unique = array => array.filter((s => v => (t => !s.has(t) && s.add(t))(serialize(v)))(new Set));

console.log(unique([10, 8, 5, 5, 8, 7]));
console.log(unique([[10, 10], [8, 8], [5, 5], [5, 5], [8, 8], [7, 7]]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.