I have an array of objects containing user information for a phone book (name, lname, phone). I am not able to render them in the order I want and want to be able to render them sorted by last name. How can I do this?
I render them in a table like this:
{persons.map((element, i) => (
<tr key={i}>
<td style={style.tableCell}>{ element.userFirstname }</td>
<td style={style.tableCell}>{ element.userLastname }</td>
<td style={style.tableCell}>{ element.userPhone }</td>
</tr>
))}
To add data to the array, I have a form that appends the data to the array whenever the submit button is pressed. This is how I append the data:
const [persons, setPersons] = useState([
{
userFirstname: "Coder",
userLastname: "Byte",
userPhone: "8885559999"
}
])
const [formData, setFormData] = useState({
userFirstname: "",
userLastname: "",
userPhone: ""
});
const { userFirstname, userLastname, userPhone } = formData;
const onChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value })
}
const onSubmit = (e) => {
e.preventDefault();
setPersons(persons.concat({ userFirstname: userFirstname, userLastname: userLastname, userPhone: userPhone }));
}
Do I need to sort the array before the map function or can I do it during the map function?