Let's say I have these arrays of object
selectedNames = [
{label: 'Nicolas', value:'Nicolas'},
{label: 'Michael', value:'Michael'},
{label: 'Sean', value:'Sean'},
{label: 'George', value:'George'}
]
selectedWhatever = [
{label: 'Guitar', value: 'Guitar'},
{label: 'Bass', value: 'Bass'}
]
and then another array of objects like this:
list = [
{name: 'Nicolas', surname: 'Smith', birthplace: 'NewYork', whatever: 'Guitar'},
{name: 'Sean', surname: 'Narci', birthplace: 'LA', whatever: 'Bass'},
{name: 'George', surname: 'Rossi', birthplace: 'NewYork', whatever: 'Bass'},
{name: 'Fiona', surname: 'Gallagher', birthplace: 'Madrid', whatever: 'Drum'},
{name: 'Michael', surname: 'Red', birthplace: 'London', whatever: 'Triangle'},
]
and I want to filter list based on the datas I have in the others two arrays and group by birthplace, so I want this:
result = {
LA: [
{name: 'Sean', surname: 'Narci', birthplace: 'LA', whatever: 'Bass'},
],
NewYork: [
{name: 'Nicolas', surname: 'Smith', birthplace: 'NewYork', whatever: 'Guitar'},
{name: 'George', surname: 'Rossi', birthplace: 'NewYork', whatever: 'Bass'},
]
}
What I've done is the following and it works fine. Is there a smarter or more elegant way to do the same?
const obj = {};
list.map((res) => {
if ((data.selectedNames.map((r) => r.label).includes(res.name))
&& (data.selectedWhatever.map((r) => r.label).includes(res.whatever))
){
result[res.birthplace] = result[res.birthplace] ?? []:
result[res.birthplace].push(res);
}
})