1

So I'm trying to group some reservations by business id. I'm looking for an end result like this:

[ [businessID1] => [Object1,Object2, Object3], [businessID2] => [Object1,Object2], [businessID3] => [Object1,Object2] ]

My current code:

let groups = new Array;
this.reservations.map(function (value) {
  groups[value.businessID] = value;
});

So right now it doesn't work... because each time it's going to re-write that array key. I'm new to the typescript/js world, any help is appreciated.

1

1 Answer 1

2

If the value does not exist, create an empty array, and append the value to it with push:

if (groups[value.businessID] === undefined) {
  groups[value.businessID] = [];
}
groups[value.businessID].push(value);

Or more compactly:

(groups[value.businessID] = groups[value.businessID] || []).push(value);
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.