I have this sample data:
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 try to end up with:
[[1, [morgan, eric]], [2, [brian, derek]], [3, [courtney]], [4, [eric, jon]]
I use the function .reduce()to display above the list. However, I am somewhat stuck.
I got this job:
let b = list.reduce((final_list, new_item) => {
x = final_list.concat([[new_item.id, [new_item.first]]])
return x
}, [])
However, this aligns the list in the list of list lists, but does not combine names that have a similar identifier.
I tried using the .map() code below does not work
I tried to display the final_list file (list [id, [names]] to see if id exists new_itemin smaller_list, and then add new_item.firstto smaller_list[1](which should be a 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
}, [])