reduce vs for loop transformation

Benchmark created on


Setup

const originalData = [{
    devicename: 'x',
    devicetype: 'zigbee'
  },
  {
    devicename: 'y',
    devicetype: 'zwave'
  },
  {
    devicename: 'z',
    devicetype: 'zwave'
  }
];

Test runner

Ready to run.

Testing in
TestOps/sec
Reduce
const transformedData = originalData.reduce((acc, item) => {
  const itemsByDevicetype = !acc[item.devicetype] ? [ item ] : [ ...acc[item.devicetype], item ];
  return Object.assign(acc, { [item.devicetype]: itemsByDevicetype });
}, {});
ready
For loop
const transformedData = {};

for (let i = 0; i < originalData.length; i++) {
  if (!transformedData[originalData[i].devicetype]) {
    transformedData[originalData[i].devicetype] = [ originalData[i] ];
  } else {
    transformedData[originalData[i].devicetype].push(originalData[i]);
  }
}
ready

Revisions

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