lodash flatten vs reduce

one year ago
User agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36
Test name Executions per second
flatten 9219310.0 Ops/sec
reduce 1425170.0 Ops/sec
HTML Preparation code:
AخA
 
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Script Preparation code:
x
 
window.obj = {};
for (var i = 0, len = 10; i < len; i++) {
  var arr = []
  obj['key' + i] = arr
  for (var n = 0, len = 10; n < len; n++) {
    arr.push({ ['key' + n]: n });
  }
}
Tests:
  • flatten

     
    _.flatten(obj, (acc, val, key) => {
      acc[key] = val.map(d => ({ label: key, value: val }));
      return acc;
    }, {})
  • reduce

     
    Object.entries(obj).reduce((acc, [key, val]) => {
      acc[key] = val.map(d => ({ label: key, value: val }));
      return acc;
    }, {})
Open this result on MeasureThat.net