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!

1 Answers1

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392