I've got an array with list of patients and they all have unique id.
this.state = {
patients = [
{id: "1", name: "Joe", age: 6, location: ''},
{id: "12", name: "Her", age: 2, location: ''},
{id: "1123", name: "Jin", age: 10, location: ''},
{id: "11234", name: "Nick", age: 23, location: ''},
{id: "12345", name: "Fil", age: 50, location: ''},
];
When a user clicks on a button it sends the paitient unique id, and location on a callback. I then use the unique id to find the patient in the patients array and update that patient's location. The way I find the patient in the array is using map to loop over the patients array, check if
the patientId
matches the id
in the array and adds the location for that patient. However, map will always go over every
patient in the patients array
so does unnecessary looping & is expensive if the array gets bigger. I know there are other ways to find the element in the
array i.e. findIndex() method
but is it any better than the map? Whats the best approach for this use case?
<Button
id={location}
onClick={() => addPatientLocation(patientId, location}
>
{location}
</Button>
Function that check if patient id matched and updates that patients details
addPatientLocation(patientId, location) {
this.setState(prevState => ({
patients: prevState.patients.map(p => {
if (p.id === patientId) {
return { ...p, location: location };
}
return p;
}),
}));
}