Jon
Jon

Reputation: 87

Map and Sort Methods for component in React?

Relatively new to React and trying to sort the mapped prop nearbyRestaurants alphabetically by place.name. Is there a way I can chain the sort method to the end of the map method to alphabetize the list?

export default function RestaurantList({nearbyRestaurants}) {
  return (
    <div>
      <ul>
        <li className="list-header">Restaurants</li>

        {nearbyRestaurants.map((place) => (
          <div>
            <li>
              <div>{place.name}</div>
              <div>{place.vicinity}</div>
            </li>
          </div>
        ))}
      </ul>
    </div>
  );
}

Upvotes: 0

Views: 32

Answers (1)

Albert Alises
Albert Alises

Reputation: 1028

Sort the array before mapping it.

function sortAlphabetically(a,b){
    return a.name.localeCompare(b.name)
}

export default function RestaurantList({nearbyRestaurants}) {
  return (
    <div>
      <ul>
        <li className="list-header">Restaurants</li>

        {nearbyRestaurants.sort(sortAlphabetically).map((place) => (
          <div>
            <li>
              <div>{place.name}</div>
              <div>{place.vicinity}</div>
            </li>
          </div>
        ))}
      </ul>
    </div>
  );
}

Upvotes: 1

Related Questions