简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM