You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js 表格排序功能开发求助:实现升降序排序逻辑

Fixing Ascending/Descending Sort for Your Table Filter Function

Hey there! I see the issue with your current code—right now you're just overwriting the field value with '1' or '0' instead of actually reordering the table data. Let's fix that sorting logic properly.

First, let's clarify: your filteredTable seems to be an object (since you're using Object.keys(filteredTable).map()), so we'll need to convert it to an array of values, sort that array, and then convert it back if your state expects an object. Here's how to adjust your filterTable function:

export function filterTable(tableList, filters) {
  let filteredTable = { ...tableList }; // Start with a copy to avoid mutating original data

  // Loop through each filter
  Object.keys(filters).forEach((filterKey) => {
    const filter = filters[filterKey];
    const fieldName = filter.field;

    // Convert object to array of values for sorting
    const tableArray = Object.values(filteredTable);

    switch (filter.type) {
      case '>': // Ascending order
        tableArray.sort((a, b) => {
          // Handle numbers vs strings correctly
          if (typeof a[fieldName] === 'number' && typeof b[fieldName] === 'number') {
            return a[fieldName] - b[fieldName];
          } else {
            // For strings, use localeCompare for proper alphabetical sorting
            return String(a[fieldName]).localeCompare(String(b[fieldName]));
          }
        });
        break;

      case '<': // Descending order
        tableArray.sort((a, b) => {
          if (typeof a[fieldName] === 'number' && typeof b[fieldName] === 'number') {
            return b[fieldName] - a[fieldName];
          } else {
            return String(b[fieldName]).localeCompare(String(a[fieldName]));
          }
        });
        break;
    }

    // Convert sorted array back to object if needed (match original structure)
    filteredTable = tableArray.reduce((acc, item) => {
      // Replace 'id' with your actual unique field name if different
      acc[item.id] = item;
      return acc;
    }, {});
  });

  return { type: 'RANKPARAM_FILTERED', payload: filteredTable };
}

Key Changes Explained:

  • Avoid Mutation: We start with a copy of tableList using { ...tableList } to prevent modifying the original state directly—critical for Redux best practices!
  • Object to Array Conversion: Object.values(filteredTable) turns your object of table rows into an array, which we can sort using JavaScript's native sort() method.
  • Proper Sort Logic:
    • For numbers: Subtract values to get ascending/descending order (since sort() expects a negative, zero, or positive return value).
    • For strings: Use localeCompare() to handle alphabetical sorting correctly, including support for accented characters.
  • Array Back to Object: If your Redux state expects an object (like the original tableList), we use reduce() to convert the sorted array back into an object, using each item's unique ID as the key.

Quick Notes:

  • If your tableList is already an array (not an object), you can skip the Object.values() and reduce() steps—just sort the array directly.
  • Make sure to replace item.id with the actual unique identifier field in your table data (e.g., item.rankId if that's your key).
  • This code applies filters sequentially. If you need to handle multiple sort criteria at once, you'd adjust the sort function to check multiple fields, but this works perfectly for single-field sorting as your current setup requires.

Hope this gets your sorting working smoothly! 🚀

内容的提问来源于stack exchange,提问作者Silvio Custodio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:29:20