2

I'm trying to sort the array alphabetically when the button is pressed but so far everything that I tried failed. The button and function work as I tried console logging something and it prints in the console. I feel like my sorting function is wrong but I'm not sure what to do about it. How can I fix this so it works?

import React from "react";
import './Brewery.css'
import { Link } from 'react-router-dom';
import { ButtonToolbar, DropdownButton, MenuItem } from 'react-bootstrap';


class Brewery extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMenu: false,
      breweries: []
    }
  }

  componentDidMount() {
    fetch("https://api.openbrewerydb.org/breweries")
      .then(response => response.json())
      .then((data) => {
        this.setState({
          breweries: data,
        })
      })
  }

  sortAlpha() {
    const breweries = [].concat(this.state.breweries)
    .sort((a, b) => a.name > b.name)
    this.setState({breweries:breweries});
  }

  render() {

    const { breweries } = this.state;

    return(
     <div className="main-container">
       <div className="banner" styles="background-image: linear-gradient(-225deg, rgba(0,101,168,0.6) 0%, rgba(0,36,61,0.6) 50%), url('http://bitterminnesotabrewerytours.com/wp-content/uploads/2014/02/boston-beer-tours-glass.jpg');">
         <div className="banner-content">
           <h1>Brewery</h1>
           <p>Find the best brewery in town</p>
         </div>
       </div>
       <div className="container">
         <div>
           <button onClick={() => this.sortAlpha()}>Sort Alphabetically</button>
         </div>
         <div className="row">
          {breweries.slice(0,10).map((brewery, i) =>
            <div className="col-xs-12 col-sm-4" key={i}>
              <Link to={`/brewery/${ brewery.id }`}>
                <div className="card">
                  <div className="card-description">
                    <h2>{brewery.brewery_type}</h2>
                    <p>{brewery.city}, {brewery.state}</p>
                  </div>
                  <div className="card-category"><img src="https://img.icons8.com/color/20/000000/beer.png"/>  {brewery.name}</div>
                </div>
              </Link>
            </div>
          )}
        </div>
      </div>
    </div>
    )
  }
}

export default Brewery;
2
  • Have you tried removing const { breweries } = this.state; and calling state directly with your map function so instead of {breweries.slice(0,10).map() try this.state.breweries.slice(0, 10).map() Commented Dec 17, 2018 at 19:02
  • It doesn't work Commented Dec 17, 2018 at 19:03

2 Answers 2

8

Try this

sortAlpha() {
    const breweries = [...this.state.breweries].sort((a, b) => {
      if (a.name < b.name) return -1;
      if (a.name > b.name) return 1;
      return 0;
    });
    this.setState({ breweries: breweries });
  }
Sign up to request clarification or add additional context in comments.

Comments

4

This is not how sort works with strings.

It should return one of three:

  • A positive number if a.value is greater than b.value .
  • A negative number if b.value is greater than a.value .
  • Zero (0) if a.value == b.value

So in your case it should be something like this:

.sort((a, b) => {
  if (a.name < b.name) { return -1; }
  if (a.name > b.name) { return 1; }
  return 0;
});

Keep in mind that sort is sorting the elements in place (mutation)

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.