首页 > 解决方案 > 如何通过 React.js 中的映射按最大值对对象数组进行排序?

问题描述

我正在尝试从 API 数据中打印值,目前,我能够以字母方式打印它。现在,我想按最大值到最小值的顺序打印。我想按最多案例到最少案例来显示数组数据。但是,我很难弄清楚如何做到这一点。这是我的代码:

API链接

import React from 'react'
import Table from 'react-bootstrap/Table';

const Result = (props) => {
  console.log('props value is:' + props.data)
  let { searchCheck, searchValue } = props;


  let update = props.data.map((item) => {

    const { countryInfo, country, cases, deaths, recovered, active, casesPerOneMillion } = item;
    return (
      (searchCheck) ? country.toUpperCase().includes(searchValue.toUpperCase()) ?
        <tbody>
          <tr key={countryInfo._id}>
            <td><img style={{ height: '25px', width: '50px' }} src={countryInfo.flag} /></td>
            <td>{country}</td>
            <td>{cases}</td>
            <td>{active}</td>
            <td>{recovered}</td>
            <th>{casesPerOneMillion}</th>
            <td>{deaths}</td>
          </tr>
        </tbody> :
        '' :
        <tbody>
          <tr key={countryInfo._id}>
            <td><img style={{ height: '25px', width: '50px' }} src={countryInfo.flag} /></td>
            <td>{country}</td>
            <td>{cases}</td>
            <td>{active}</td>
            <td>{recovered}</td>
            <th>{casesPerOneMillion}</th>
            <td>{deaths}</td>
          </tr>
        </tbody>
    )
  })
  return (
    <div>
      <Table striped bordered hover variant="dark">
        <thead>
          <tr>

            <th>Flag</th>
            <th>Country</th>
            <th>Cases</th>
            <th>Active</th>
            <th>Recovered</th>
            <th>Cases per one Million</th>
            <th>Deaths</th>


          </tr>
        </thead>
        {update}
      </Table>
    </div>
  )
}
export default Result;

标签: reactjsecmascript-6

解决方案


你可以简单地这样做:

var sortedData = [...data].sort((a, b) => b.cases - a.cases)

在这里,data实际上是props.data您正在使用的。

演示:

(async() => {
  let response = await fetch('https://corona.lmao.ninja/countries?sort=country');
  let data = await response.json(); // read response body as json
  var sortedData = [...data].sort((a, b) => b.cases - a.cases)  
  
  // Showing only top 10 country case counts
  console.log(sortedData.slice(0, 10).map(({country, cases}) => ({ country, cases})));
})();
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读