obj vs reduce

Benchmark created on


Setup


const result1 = {
    politeness: 0,
    resolution: 0,
    grammar: 0,
    customerSatisfaction: 0,
  };
  
const dataAvg = (d) => d.reduce((acc, obj) => {
    (Object.keys(obj)).forEach((key) => {
      if (key === "inquiry") {
        return;
      }
      acc[key] = (acc[key] + obj[key]) / d.length;
    });
    return acc;
  }, result1);
  
  function getMostConsistentObject(data) {
 
  const result = {
    politeness: 0,
    resolution: 0,
    grammar: 0,
    customerSatisfaction: 0,
  };

  data.forEach((obj) => {
    (Object.keys(obj)).forEach((key) => {
      if (key !== "inquiry") {
        if (!result[key]) {
          result[key] = 0;
        }
        result[key] += obj[key];
      }
    });
  });

  (Object.keys(result)).forEach((key) => {
    result[key] = Math.round(result[key] / data.length);
  });

  return result;
}

 

Test runner

Ready to run.

Testing in
TestOps/sec
With reduce
const analysisArray = [
  {
    politeness: 8,
    resolution: 0,
    grammar: 10,
    customerSatisfaction: 0
  },
  {
    politeness: 9,
    resolution: 0,
    grammar: 10,
    customerSatisfaction: 0
  },
  {
    politeness: 8,
    resolution: 0,
    grammar: 7,
    customerSatisfaction: 0
  }
];
dataAvg(analysisArray)
ready
With foreach
const data = [
  {
    politeness: 8,
    resolution: 0,
    grammar: 10,
    customerSatisfaction: 0
  },
  {
    politeness: 9,
    resolution: 0,
    grammar: 10,
    customerSatisfaction: 0
  },
  {
    politeness: 8,
    resolution: 0,
    grammar: 7,
    customerSatisfaction: 0
  }
];

getMostConsistentObject(data)
ready

Revisions

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