1

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?

3 Answers 3

4

You can do wherever you want, during the setting of state or during rendering.

I'd go with doing it in map i.e rendering as an array, as its just shuffling of data. This way my original state list is ordered by 'last modified', which might come handy later.

So to sort them alphabetically via last name, you can use the sort method.

{persons.sort((a,b) => a.userLastname.localeCompare(b.userLastname))).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>
))}
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this:

You have to install lodash library: npm i --save lodash

import {sortBy} from 'lodash';


{sortBy(persons, ['userLastname']).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>
))}

Comments

0

i suggest you to sort the array before setting the state because otherwise in every render it will try to sort it before showing it.

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.