map vs foreach to fill in Set

Benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
map
const arrayOfObjects = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' },
  { id: 4, name: 'Alice' },
];

const idSet = new Set(arrayOfObjects.map(obj => obj.id));
console.log(idSet);
ready
forEach
const arrayOfObjects = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' },
  { id: 4, name: 'Alice' },
];
const idSet = new Set();
arrayOfObjects.forEach((obj) => {
	idSet.add(obj.id);
})
console.log(idSet);
ready

Revisions

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