Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot sort array of objects in react

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;
like image 664
razvanusc Avatar asked Jun 05 '26 00:06

razvanusc


1 Answers

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 });
  }
like image 119
Alejandro Gonzalez Avatar answered Jun 07 '26 13:06

Alejandro Gonzalez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!