Test name | Executions per second |
---|---|
Lodash with _.mapValues and _.omit | 2.8 Ops/sec |
Native reduce Grouping with Destructuring | 14.5 Ops/sec |
Custom reduce with Object.keys Filtering | 8.4 Ops/sec |
Lodash Grouping with Native Key Removal | 44.2 Ops/sec |
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
const max2 = 500000;
var rows = [];
for (let i = 0; i <= max2; i++) { // Use `let` for `i` as it’s updated in each loop iteration
rows.push({
id: i,
task_id: i % 1000,
name: `Task ${i}`,
status: i % 2 === 0 ? 'active' : 'inactive',
description: `Description for task ${i}`,
priority: Math.floor(Math.random() * 5) + 1
});
}
const lodashMapValuesOmitGrouped = _.mapValues(_.groupBy(rows, 'task_id'), group =>
group.map(row => _.omit(row, 'task_id'))
);
const nativeReduceGrouped = rows.reduce((acc, row) => {
const { task_id, rest } = row; // Exclude `task_id` using destructuring
if (!acc[task_id]) acc[task_id] = []; // Initialize array for this `task_id`
acc[task_id].push(rest); // Add the item without `task_id` to the group
return acc;
}, {});
const customReduceGrouped = rows.reduce((acc, row) => {
if (!acc[row.id]) acc[row.id] = []; // Initialize an array for each unique id
const rowData = Object.keys(row).reduce((obj, key) => {
if (key !== 'id') obj[key] = row[key]; // Exclude 'id' to avoid nesting
return obj;
}, {});
acc[row.id].push(rowData);
return acc;
}, {});
const lodashGroupedWithDelete = _.groupBy(rows, 'task_id');
Object.values(lodashGroupedWithDelete).forEach(group => {
group.forEach(item => {
delete item.task_id; // Remove `task_id` directly from each item
});
});