javascript - Cannot sort array of objects in react - Stack Overflow

I'm trying to sort the array alphabetically when the button is pressed but so far everything that

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: []
    }
  }

  ponentDidMount() {
    fetch("")
      .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('.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=".png"/>  {brewery.name}</div>
                </div>
              </Link>
            </div>
          )}
        </div>
      </div>
    </div>
    )
  }
}

export default Brewery;

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: []
    }
  }

  ponentDidMount() {
    fetch("https://api.openbrewerydb/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./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./color/20/000000/beer.png"/>  {brewery.name}</div>
                </div>
              </Link>
            </div>
          )}
        </div>
      </div>
    </div>
    )
  }
}

export default Brewery;
Share Improve this question asked Dec 17, 2018 at 18:55 razvanuscrazvanusc 1793 silver badges15 bronze badges 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() – Ids van der Zee Commented Dec 17, 2018 at 19:02
  • It doesn't work – razvanusc Commented Dec 17, 2018 at 19:03
Add a ment  | 

2 Answers 2

Reset to default 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 });
  }

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)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743747615a4500298.html

相关推荐

  • javascript - Cannot sort array of objects in react - Stack Overflow

    I'm trying to sort the array alphabetically when the button is pressed but so far everything that

    6天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信