Home > Software design >  ReactJS: Multiple Sort in Table
ReactJS: Multiple Sort in Table

Time:04-05

I have the following code in React. This sorts by Owner and then Category. I want to also sort by Brand, so Owner -> Category -> Brand.

If I put another .sort function in then it will sort by Brand, but ignore Category. Any idea how to rewrite this so I can get a 3 level sort?

{
  categorizedDatas2[key]?.items
    .sort(function (aa, ab) {
      var textAA = aa.Category.toUpperCase();
      var textAB = ab.Category.toUpperCase();
      return textAA < textAB ? -1 : textAA > textAB ? 1 : 0;
    })
    .sort(function (c, d) {
      var textC = c.Owner.toUpperCase();
      var textD = d.Owner.toUpperCase();
      return textC < textD ? -1 : textC > textD ? 1 : 0;
    })
    .map((item, index) => {
      return (
        <TableRow key={item.id}>
          <TableCell data-title='Category'>{item.Owner}</TableCell>
          <TableCell className='topright' data-title='GCat'>
            {item.Category}
          </TableCell>
          <TableCell data-title='Name'>{item.Brand}</TableCell>
          <TableCell data-title='Name'>
            {item.Name} x {item.Quantity}
          </TableCell>
        </TableRow>
      );
    });
}

CodePudding user response:

Try to change your sort function like this:

{
    categorizedDatas2[key]?.items
      .sort(function (aa, ab) {
        var categoryA = aa.Category.toUpperCase();
        var categoryB = ab.Category.toUpperCase();
        if (categoryA !== categoryB) {
          // Sort by category
          return categoryA < categoryB ? -1 : 1;
        }
        var ownerA = aa.Owner.toUpperCase();
        var ownerB = ab.Owner.toUpperCase();
        if (ownerA !== ownerB) {
          // Sort by owner
          return ownerA < ownerB ? -1 : 1;
        }
        var brandA = aa.Brand.toUpperCase();
        var brandB = ab.Brand.toUpperCase();
        // Sort by brand
        return brandA < brandB ? -1 : 1;
      })
      .map((item, index) => {
        return (
          <TableRow key={item.id}>
            <TableCell data-title='Category'>{item.Owner}</TableCell>
            <TableCell className='topright' data-title='GCat'>
              {item.Category}
            </TableCell>
            <TableCell data-title='Name'>{item.Brand}</TableCell>
            <TableCell data-title='Name'>
              {item.Name} x {item.Quantity}
            </TableCell>
          </TableRow>
        );
      });
  }
  
  • Related