0

I've implement uniqBy method as following.

Array.prototype.uniqBy = function (iteratee) {
  let uniques = [];
  for (let a of this) {
    const mappedUniques = uniques.map(iteratee);
    if (!mappedUniques.includes(iteratee(a))) {
      uniques.push(a);
    }
  }
  return uniques;
}

How to use this method:

let arrays = [
    {id: 1, value: 'm'},
    {id: 2, value: 'cm'},
    {id: 3, value: 'km'},
    {id: 2, value: 'cm2'}
];

console.log(arrays.uniqBy(x => {return x.id}));

After this, will removed duplicate ids. So

[
    {id: 1, value: 'm'},
    {id: 2, value: 'cm'},
    {id: 3, value: 'km'}
]

But it's performance is not good.
Where is more good performance method or library?

Anyone please advice. Thanks.

Daniel.Wang
  • 2,242
  • 2
  • 9
  • 27

1 Answers1

2

Make a separate Set of the unique primitives instead of using an array; set lookup is much, much faster than an array's .includes. Instead of mapping the uniques each time in the loop, use the separate Set.

function (iteratee) {
    const uniquePrimitives = new Set();
    return this.filter((item) => {
        const prim = iteratee(item);
        if (!uniquePrimitives.has(prim)) {
            uniquePrimitives.add(prim);
            return true;
        }
    });
}

As has been said, I'd highly recommend against mutating built-in prototypes.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320