Finding unique keys across the list of records

Benchmark created on


Setup

const makeKey = () => Math.floor(Math.random() * 30); // number 0-29
const makeKeysAmount = () => (5 + Math.round(Math.random() * 10)); // number 5-15
const makeRecordKeys = () => Array(makeKeysAmount()).fill(0).map(() => makeKey()); // array of random amount of random numbers
const makeRecord = () => makeRecordKeys().reduce((o, k) => {
  o[k] = true;
  return o;
}, {}); // object like `{ 9: true, 14: true, 17: true, 24: true, 26: true, 29: true }`

const input = Array(1000).fill(0).map(() => makeRecord());

Test runner

Ready to run.

Testing in
TestOps/sec
Double loop
const keys = new Set();

input.forEach(o => {
  Object.keys(o).forEach(k => {
    keys.add(k);
  });
});

const result = Array.from(keys);
ready
Union
let keys = new Set();

input.forEach(o => {
  keys = keys.union(new Set(Object.keys(o)));
});

const result = Array.from(keys);
ready
Collect then deduplicate
const keys = [];

input.forEach(o => {
  keys.push(...Object.keys(o))
});

const result = Array.from(new Set(keys));
ready

Revisions

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