Reduce v foreach

Benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
reduce
const Units = [
  { id: 12345, foo: true, bar: false },
  { id: 23456, foo: false, bar: true },
  { id: 34567, foo: false, bar: true },
  { id: 45678, foo: false, bar: true },
  { id: 56789, foo: true, bar: false },
  { id: 67890, foo: true, bar: false },
];

const { fooUnits, barUnits } = Units.reduce(
    (memo, unit) => ({
      ...memo,
      fooUnits: memo.fooUnits.concat(unit.foo ? [unit.id] : []),
      barUnits: memo.barUnits.concat(unit.bar ? [unit.id] : [])
    }),
    { fooUnits: [], barUnits: [] }
);
console.log(fooUnits, barUnits);

ready
forEach
const Units = [
  { id: 12345, foo: true, bar: false },
  { id: 23456, foo: false, bar: true },
  { id: 34567, foo: false, bar: true },
  { id: 45678, foo: false, bar: true },
  { id: 56789, foo: true, bar: false },
  { id: 67890, foo: true, bar: false },
];

const errors = { fooUnits: [],  barUnits: [] };
Units.forEach(
    (unit) => {
      if (unit.foo) {
      	errors.fooUnits.push(unit);
      }	
      if (unit.bar) {
      	errors.barUnits.push(unit);
      }	
    },
);
console.log(errors);
ready

Revisions

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