Grouping

Benchmark created on


Description

Compare 3 groupings

  1. for of
  2. reduce
  3. groupBy

Setup

const arr = [
  { date: '2024/02/05', price: '1400' },
  { date: '2024/02/06', price: '1400' },
  { date: '2024/02/07', price: '2000' },
  { date: '2024/02/08', price: '2000' },
  { date: '2024/02/09', price: '2000' },
  { date: '2024/02/10', price: '2500' },
  { date: '2024/02/11', price: '2500' }
];

Test runner

Ready to run.

Testing in
TestOps/sec
For of
const grouped = {};
for (const {date, price} of arr) {
  grouped[price] ??= { price, date: [] }; // Initialize if not already
  grouped[price].date.push(date);
}

const result = Object.values(grouped);
ready
Reduce
const result = Object.values(arr.reduce((acc, {date, price}) => {
  acc[price] ??= {price, date: []};
  acc[price].date.push(date);
  return acc;
}, {}));
ready
groupBy
const result = 
 Object.entries(
   Object.groupBy(arr, (item) => item.price)
  ).map(([price, entries]) => ({ price, date: entries.map(({ date }) => date) }));
ready

Revisions

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