Reputation: 292
I have an array like so:
reportData = [
{status: "Resolved", type: Placement of bins},
{status: "Assigned", type: Placement of bins},
{status: "Active", type: Sewerage}
]
Now this is what I am trying to do. I want to make as many checkboxes as the count of reportData array but also remove the duplicated values, like in this case, I want "Placement of bins" only once (one checkbox). So overall according to the array there should be only 2 checboxes, but I'm getting three because obviously there are 3 objects in the array.
{
reportData.map((obj) => {
return (
<FormControlLabel
value="type"
control={<Checkbox color="primary" />}
label={obj.type}
labelPlacement="end"
/>
)
})
}
Is there some way to first sort out the duplicated array of objects and maybe then I can map it?
Upvotes: 0
Views: 6356
Reputation: 1009
Here is what I would do,
const mapped = reportData.map((obj, index) => obj.type);
const filtered = mapped.filter((type, index) => mapped.indexOf(type) === index )
Here is what happened, map
function made a new array called mapped
that has the all types you had in reportData
including duplicates.
filter
filtered the duplicates as; array.indexOf(element)
returns index of the first element that matches. Here, 'Placement of bins'
is in 0
and 1
indexes. So the iterations be like true false true
since in first iteration it is 0 === 0
, in second: it's 0 === 1
and in third it's 2===2
. So filtered array only gets the elements of index 0
and 2
And then using the filtered array to map to get checkboxes.
Upvotes: 2
Reputation: 111
You could use lodash method _.uniqBy, it is available in the current version of lodash 4.17.2.
Example:
_.uniqBy([{status:"Resolved", type:'Placement of bins'},
{status:"Assigned", type:'Placement of bins'},
{status:"Active", type:'Sewerage'}], 'type');
// => [{status: "Resolved", type: "Placement of bins"}, {status: "Active", type: "Sewerage"}]
More info: https://lodash.com/docs/#uniqBy
Upvotes: 1