javascript MUI数据表中已选中复选框的排序

kzmpq1sx  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(110)

我想已经检查的数据是在MUI数据表的顶部。Checkobx在这里你看到在这个图像中所有的复选框都没有排序。
所以我想把所有选中的行都放在一起,并且放在数据表的顶部。
请帮我调查这个案子。

gmol1639

gmol16391#

下面给出了一个解决方案,即函数SortCheckedAtTop。要使该解决方案正常工作,需要将行列表表示为对象数组(rows)。需要使用行ID数组来维护选中行的列表(selected)。rowsselelcted都应该使用某种状态管理方法来维护(例如Redux,React.useState,React.useReducer等)。
一般的排序可以使用JavaScript的Intl.Collator来处理。例如:

let collator = new Intl.Collator( 'en', { numeric: false, sensitivity: 'base' } );

function getSortedRows = ( rows ) => {
    rows.sort( ( a, b ) => {
        return collator.compare( a.value, b.value );
    } );
    return rows;
}

函数SortCheckedAtTop基于这里的排序函数。该函数假设rows是之前排序的对象列表。对象可能看起来像这样:

const rows = [
    {
        id: 0,
        value: 'something'
    },
    {
        id: 1,
        value: 'something else'
    },

    ...

];

selectedid的数组,表示被检查的行。如果使用React.useState来管理这个数组,您可能会有一个类似于以下的语句:

// 'zero' is the ID of a row that is checked.
const [ selected, setSelected ] = React.useState( [ 0 ] );

解决方案

/**
 * Sort function.
 */
function SortCheckedAtTop( rows ) {
    let ids = rows.map( ( row ) => row.id );

    // Spread operator is used to avoid overwriting the original sort order of `rows`.
    // You might want to preserve the original sort order of `rows` to use it later.
    // in this function.
    let resorted = [ ...rows ].sort(
        ( a, b ) => {

            // Display the checked rows first.
            let ai = selected.indexOf( a.id ); // Index for row a.

            // If a.id is not in the selected list ai will be -1.
            // If -1, update ai by placing it at the end of the list of
            // selected rows. The end position is calculated using
            // ( selected.length ).
            // But we need to maintain the original order of unselected rows.
            // So, we add the position index from the original rows array:
            // ( ids.indexOf( a.id ) ).
            // If the selected list had 4 IDs, 'a' was not selected,
            // and a.id were in position 3 in the original list of rows
            // (zero-based array index = 2), ai would be 4 + 2 = 6.
            // This maintains the same order as the original list of rows.
            ai = ai === -1 ? selected.length + ids.indexOf( a.id ) : ai;

            // Update bi if needed.
            let bi = selected.indexOf(b); // Index for row b.
            bi = bi === -1 ? selected.length + ids.indexOf( b.id ) : bi;

            // Return the sort result.
            // negative value: ascending,
            // positive value: descending,
            // zero: undetermined (you can add more code to sort by another sort key)
            return ai - bi;
        }
    );

    return resorted;
}

相关问题