I have a list of objects that contain peoples names and their service times. These names can occur more than once throughout this list, and the service times can be different for each occurrence. What I'm trying to do is create a HashSet of names with an index attached to it so that I can reference it back to the larger list without having to create a nested for loop. For instance if I have the list:
[{Name: 'john doe', ServiceTime: '20min'}, {Name: 'john doe', ServiceTime: '25min'},
{Name: 'john doe', ServiceTime: '31min'}, {Name: 'billy bob', ServiceTime: '1min'},
{Name: 'billy bob', ServiceTime: '12min'}, {Name: 'john doe', ServiceTime: '19min'}]
And i create my HashSet to look like this:
{'john doe': 0, 'billy bob': 1}
Here is how I'm doing it:
let count = 0;
list.map(obj => arr[obj.Name] = arr[obj.Name] ? arr[obj.Name] : count++)
The value of the key is incremented each time a NEW person is found, if that makes sense. After this is complete I iterate through the new object of names that I've created, to create an array of objects, which will hold the persons name and an array to hold their service times like so:
[{Name: 'john doe', ServiceTimes:[]}, {Name: 'billy bob', ServiceTimes:[]}]
With this information I can go back and iterate through my initial list updating the index to search for by the key value pair of my HashSet like this:
list.map(obj => {
let index = arr[obj.Name];
if(temp[index] !== undefined){
temp[index].ServiceTimes.push(obj)
}
})
The issue that I'm facing is that after creating my HashSet, I notice that I'm getting an off by 1 error with my indices. For example, the list that i provided above gives me the HashSet:
{'john doe': 1, 'billy bob': 2}
and with other lists i get the HashSet
{'john doe': 0, 'billy bob': 1}
I obviously want my HashSet to look like the last one but can't seem to understand why my count is being added twice in some scenarios and not in others. If anyone could point me in the right direction or understands what I might be doing wrong that's causing this issue, I would greatly appreciate it. Thanks!
P.S. Sorry for the long question.