Unique Items by Key Map vs Filter

Benchmark created on


Setup

const array = Array.from({ length: 100000 }).map((_, i) => ({ lol: i }));

Test runner

Ready to run.

Testing in
TestOps/sec
Map
const uniqueItems = (items, key) => {
  const map = new Map();
  for (const item of items) {
    if (!map.has(item[key])) map.set(item[key], item);
  }
  return [...map.values()];
};

uniqueItems(array, 'lol');
ready
Filter
const uniqueItems = (items, key) => {
  return items.filter((newElement, index, source) => {
    return source.findIndex((sourceElement) => sourceElement[key] === newElement[key]) === index;
  });
};

uniqueItems(array, 'lol');
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.