Search code examples
lodash

Is there an inverse of _.groupBy?


I am using lodash and have grouped an array of objects on a key that they shared; I then do calculations to these objects in these groups but now I need to ungroup.

Is there any way to do this in lodash?

Thanks


Solution

  • You can use _.flatMap() to "ungroup", but it won't restore the original order:

    const arr = [2, 3, 4, 2, 3, 4]
    
    const grouped = _.groupBy(arr)
    
    console.log(JSON.stringify(grouped))
    
    const ungrouped = _.flatMap(grouped)
    
    console.log(JSON.stringify(ungrouped))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>