1

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

4
  • for loops are the most efficient iterators in JS. You will need to iterate these. You might consider using a generator function that yields each of the objects in the original array to handle them individually. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…* Commented Apr 22, 2018 at 1:24
  • it's got to be forEach bruv: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Apr 22, 2018 at 1:25
  • 1
    Traditional. for loops are faster than forEach(). Measure it yourself with jsperf.com Commented Apr 22, 2018 at 1:28
  • @RandyCasburn very true. shit as that is. Commented Apr 22, 2018 at 1:43

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.