flowen
flowen

Reputation: 536

How to order ascending by highest price using React?

I have a component that receives offers and want to set the highest on top. This is the code:

var Offerslist = React.createClass({
  _renderOffers: function(key) {
    var details = this.props[key];

    // TODO: set order of highest offer descending

    return (
      <li key={key} className="offer-of-item">
        &euro; {details.price}
        <a className="remove-offer" onClick={this._removeOffer}>X</a>
      </li>
    )
  },
  render : function() {
    return (
      <ol className="list-of-offers-per-item">
        {Object.keys(this.props).map(this._renderOffers)}
      </ol>
    )
  }
});

I thought of populating an array with objects {price:123, offerid:'foo123'} and then use .sort by price. But I can't populate an array like this as it never iterates through all objects at once. Is there perhaps some built-in React way to do this?

data: data

Upvotes: 1

Views: 1391

Answers (1)

pawel
pawel

Reputation: 36985

For a ordinary array you'd use the sort method. But since your offers is an object, not an array, you can sort the keys by looking up the price in the offers object like this:

Object.keys(this.props)
   .sort((a, b) => ( this.props[a].price - this.props[b].price ))
   .map( this._renderOffers)

Upvotes: 1

Related Questions