lodash group array of objects code example

Example 1: lodash groupby return array

export const groupArrayBy = (arr, groupBy) => {

    let newArr = []
    arr.map((item) => {
        if(item[groupBy]) {
            let finded = newArr.filter((newItem) => newItem[groupBy] === item[groupBy])
            if(finded.length > 0) {
                finded[0].products.push(item)
            } else {
                newArr.push({category: item[groupBy], products: [item]})
            }
        }
    })

    return newArr
}

Example 2: lodash groupby return array

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>