in Javascript

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

[
   "Name 1" : [
       { name: "Name 1", value: 15 },
       { name: "Name 1", value: 30 },
   ],
   "Name 2" : [
       { name: "Name 2", value: 45 },
       { name: "Name 2", value: 70 }
   ],
]

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email