Javascript group objects by property [closed]

A few lines of modern JavaScript will get you the result you want:

var dateArr = Object.values(list.reduce((result, {
    date,
    type,
    amount
}) => {
    // Create new group
    if (!result[date]) result[date] = {
        date,
        activities: []
    };
    // Append to group
    result[date].activities.push({
        type,
        amount
    });
    return result;
}, {}));

Explaination:

  1. Use Array.reduce to consolidate the list into a set of results, a plain object, grouped by date.
  2. The consolidate function destructure the item into three parameters.
  3. It then creates a new group if necessary.
  4. Current item’s type and amount is then pushed to the group as part of an object literal.
  5. The same set is returned to the reduce, so that the next item will consolidate into the same set.
  6. Use Object.values to extract the values from the set. (Drop the keys)

Leave a Comment