I have this sample data set:
let list = [
{'first': 'morgan', 'id': 1},
{'first': 'eric', 'id': 1},
{'first': 'brian', 'id': 2 },
{'first': 'derek', 'id' : 2},
{'first': 'courtney', 'id': 3},
{'first': 'eric', 'id': 4},
{'first': 'jon', 'id':4},
]
I am trying to end up with this:
[[1, [morgan, eric]], [2, [brian, derek]], [3, [courtney]], [4, [eric, jon]]
I am using the .reduce() function to map over the list. However, I'm somewhat stuck.
I got this working:
let b = list.reduce((final_list, new_item) => {
x = final_list.concat([[new_item.id, [new_item.first]]])
return x
}, [])
However, that flattens out the list into a list of lists of lists, but doesn't combine names that share a similar id.
I tried using .map() the code below does not work
I tried to map over the final_list (which is a list of [id, [names]] looking to see if the id of the new_item exists in the smaller_list and then add new_item.first to the smaller_list[1] (which should be the list of names).
Is this the right approach?
let b = list.reduce((final_list, new_item) => {
final_list.map((smaller_list) => {
if (smaller_list.indexOf((new_item.id)) >=0) {
smaller_list[1].concat(new_item.first)
// not sure what to do here...
} else {
// not sure what to do here either...
}
})
x = final_list.concat([[item.id, [item.first]]])
return x
}, [])