Search code examples
javascriptlodash

Group array of objects by key


I've got an array of objects containing IDs (non unique)

[ { a: 1 }, { a: 1 }, { a: 2 }, { a: 1 }, { a: 1 }, { a: 1 } ]

I'm trying to group objects by their keys, for example:

[   [{ a: 1 }, { a: 1 }],   [{ a: 2 }],   [{ a: 1 }, { a: 1 }, { a: 1 }]   ]

Initially I thought to iterate over each object, recursively checking all previous keys - but as the list is going to contain hundreds of objects, that would be inefficient.

Is there an inbuilt lodash method that would be suitable for this? or else what would be the best approach


Solution

  • Your question is difficult to understand, but going purely by your single input/output example (without knowing the underlying structure of your data), you could do something like the following:

    var input = [ { a: 1 }, { a: 1 }, { a: 2 }, { a: 1 }, { a: 1 }, { a: 1 } ]
    
    // function that compares equality of your objects
    function matches(a, b){
      return ...
    }
    
    var output = [[input[0]]]
    var cur = output[0]
    for(var i=1; i<input.length; i++){      
      // if the next item doesn't match the previous,
      // create the next sub array
      if(!matches(input[i], input[i-1])){ 
        cur = [input[i]]
        output.push(cur)
      }
      cur.push(input[i])
    }
    

    However, by the look of your data and requirement, it would seem like you might need to rethink your data structure.