0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it works prefectly. But can u please tell me what's happening in the second line?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.