how to get all object that has the same id in array?

I have an array of objects and I want to re-shape them based on a similar id “itemId”

array = [
{"choicesId": 2, "itemId": 40, "optionChoicesId": 4},
{"choicesId": 11, "itemId": 40, "optionChoicesId": 14},
{"choicesId": 141, "itemId": 41, "optionChoicesId": 104},
{"choicesId": 311, "itemId": 41, "optionChoicesId": 1987}
];

expected array

[
  {"id":40,"selected_ids":[{"choicesId":2},{"choicesId":11}]},
  {"id":41,"selected_ids":[{"choicesId":141},{"choicesId":311}]},
  ...
]