在 React 中对对象数组进行排序

在 React 中对对象数组进行排序:

  1. 创建数组的浅拷贝。
  2. 调用数组的 sort() 方法,传递给它一个函数。
  3. 该函数用于定义排序顺序。
export default function App() {
  const employees = [
    {id: 4, name: 'Dean', country: 'Denmark'},
    {id: 3, name: 'Carl', country: 'Canada'},
    {id: 2, name: 'Bob', country: 'Belgium'},
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 5, name: 'Ethan', country: 'Egypt'},
  ];

  // ?️ 按数字属性升序 (1 - 100) 排序
  const numAscending = [...employees].sort((a, b) => a.id - b.id);
  console.log(numAscending);

  // ?️ 按数字属性降序 (1 - 100) 排序
  const numDescending = [...employees].sort((a, b) => b.id - a.id);
  console.log(numDescending);

  // ?️ 按字符串属性升序 (A - Z) 排序
  const strAscending = [...employees].sort((a, b) =>
    a.name > b.name ? 1 : -1,
  );
  console.log(strAscending);

  // ?️ 按字符串属性降序 (A - Z) 排序
  const strDescending = [...employees].sort((a, b) =>
    a.name > b.name ? -1 : 1,
  );
  console.log(strDescending);

  return (
    <div>
      {numAscending.map(employee => {
        return (
          <div key={employee.id}>
            <h2>id: {employee.id}</h2>
            <h2>name: {employee.name}</h2>
            <h2>country: {employee.country}</h2>

            <hr />
          </div>
        );
      })}
    </div>
  );
}

这些示例展示了如何按升序和降序对数字和字符串属性的对象数组进行排序。

Array.sort 方法改变了原始数组,因此我们使用扩展语法 (...) 在调用 sort() 之前创建数组的浅表副本。

我们传递给 sort 方法的参数是一个定义排序顺序的函数。

sort() 方法使用以下逻辑对数组中的元素进行排序:

  • 如果比较函数的返回值大于0,则将b排在a之前。
  • 如果比较函数的返回值小于0,则将a排在b之前。
  • 如果 compare 函数的返回值等于 0,则保持 a 和 b 的原始顺序。

我们可以使用 Array.map 方法来呈现已排序的数组。

export default function App() {
  const employees = [
    {id: 4, name: 'Dean', country: 'Denmark'},
    {id: 3, name: 'Carl', country: 'Canada'},
    {id: 2, name: 'Bob', country: 'Belgium'},
    {id: 1, name: 'Alice', country: 'Austria'},
    {id: 5, name: 'Ethan', country: 'Egypt'},
  ];

  return (
    <div>
      {[...employees]
        .sort((a, b) => a.id - b.id)
        .map(employee => {
          return (
            <div key={employee.id}>
              <h2>id: {employee.id}</h2>
              <h2>name: {employee.name}</h2>
              <h2>country: {employee.country}</h2>

              <hr />
            </div>
          );
        })}
    </div>
  );
}

我们在排序后立即链接了对 map() 方法的调用。 如果我们只需要渲染它,这使我们能够避免将排序后的数组存储在中间变量中。re