在React&中排序数组值的单个索引JSX [英] Sorting single index of Array value in React & JSX

查看:94
本文介绍了在React&中排序数组值的单个索引JSX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对表中的行进行排序,并在状态为动态变化的状态下给定"sortBy"值,以更改每一列,但用于排序的功能未正确对值进行排序. 该函数当前正在排序,但是它对整个数组而不是选定的sortBy值进行排序我该如何解决此函数,因此它对单个列而不是整个数组进行排序,就像现在所做的那样

I'm trying to sort rows of a table and change each column given the "sortBy" value in the state the state is dynamically changing but the function to sort isn't sorting the values properly . The function is currently sorting but its sorting the entire array instead of the selected sortBy value how do I fix this function so it sorts a single column rather then the entire array like its doing now

这是我的状态:

state = {
  columnHeaders: ["Meat", "Protein", "Calories", "Carbohydrates", "Fat"],
  rows: [
    ["chicken breast", "25", "200", "37", "8"],
    ["fried chicken", "45", "450", "21", "16"],
    ["baked fish", "15", "250", "30", "9"]
  ],
  sortedBy: "",
  order: "desc",
  query: "all"
};



const { columnHeaders, rows, query, sortedBy, order } = this.state;

const newRows = query === "all" 
  ? rows
  : rows.filter(row => row[0].includes(query));

const sortedRows = sortedBy === ""
  ? newRows
  : newRows.sort((a, b) => {
   const valueA = a[columnHeaders.indexOf(sortedBy)];
   const valueB = b[columnHeaders.indexOf(sortedBy)];
    let sortedValue = 0;
    if (valueA < valueB) {
      sortedValue = -1;
    } else if (valueA > valueB) {
      sortedValue = 1;
    }
    if (order === "desc") {
      // if descending order, turn around the sort order
      sortedValue *= -1;
    }
    return sortedValue;
  });

这是渲染sortedRows变量的地图

This is the map thats rendering the sortedRows variable

{
  sortedRows.map((row, i) => (
    <TableRow key={`thc-${i}`}>
      <TableItem row={row} />
    </TableRow>
  ));
}

推荐答案

您可以使用 localeCompare sort行.

此外,由于sort更改了原始数组,因此我添加了slice来复制数组

Also, I have added slice to copy the array since sort mutates the original array

const columnHeaders = ["Meat", "Protein", "Calories", "Carbohydrates", "Fat"];
const rows = [
    ["chicken breast", "25", "200", "37", "8"],
    ["fried chicken", "45", "450", "21", "16"],
    ["baked fish", "15", "250", "30", "9"]
  ];

const sortedBy = "Meat", order = "desc";

const newRows = rows.slice().sort((a, b) => {
  const valueA = a[columnHeaders.indexOf(sortedBy)];
  const valueB = b[columnHeaders.indexOf(sortedBy)];

  let sortedValue = 0;

  if (!isNaN(valueA) && !isNaN(valueB))
    sortedValue = valueA - valueB
  else
    sortedValue = valueA.localeCompare(valueB)

  if (order === "desc") {
    sortedValue *= -1;
  }
  return sortedValue;
})

console.log(newRows)

这篇关于在React&amp;中排序数组值的单个索引JSX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆