2

I want to create a sort-by function to sort the ice creams by taste either asc or desc. My issue is that I have trouble accessing the tastes dynamically. I can access individual taste values via iceCreams[0].taste, but this is no good if I want to create a sort by button:

  state = {
    iceCreams: [
      {
        name: 'Zap',
        taste: 6,
        img:
          'blah1'
      },
      {
        name: 'Feast',
        taste: 8,
        img:
          'blah2'
      },
      {
        name: 'Mini-Milk',
        taste: 2,
        img:
          'blah3'
      }
    ]},
Moji Izadmehr
  • 2,434
  • 13
  • 19
Rowandinho
  • 193
  • 4
  • 14

1 Answers1

1

You can simply use the sort function in javascript. For example, in order to sort an array of icecreams, you can use code:

iceCreams.sort((a,b)=>a.taste-b.taste)

So your function can look like this:

const sort = (type = "asc") => {
  const { iceCreams } = this.state;
  const multiplier = type === "asc" ? +1 : -1;
  const sortedIceCreams = iceCreams.sort(
    (a, b) => multiplier * (a.taste - b.taste)
  );
  this.setState({iceCreams : sortedIceCreams})
};

It takes a type ('asc' or otherwise) and uses the above function to sort iceCreams.

Moji Izadmehr
  • 2,434
  • 13
  • 19