Source: paulund.co.uk

JavaScript GroupBy Function
Below is a helper function you can use to take an array and group by a key. const groupBy = function (data, key) { return data.reduce(function (carry, el) { var group = el[key]; if (carry[group] === undefined) { carry[group] = []} carry[group].push(el) return carry }, {})}export { groupBy} You can use this on your arrays by passing in your array with the key you want to group on. let array = [{ name: "Name 1", value: 15 }, { name: "Name 1", value: 30 }, { name: "Name 2", value: 45 }, { name: "Name 2", value: 70 }]console.log( groupBy(array, 'name')) This will output the new array as
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners