reactjs - 如何通过 React.js 中的映射按最大值对对象数组进行排序?
问题描述
我正在尝试从 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;
解决方案
你可以简单地这样做:
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; }
推荐阅读
- vue.js - 使用 Prettier 在 Vue 模板中保留垂直空格
- ios - 外部显示器上的 iOS PDFView 部分模糊
- node.js - 在数组上填充 + 聚合
- php - PHP/SQL - 如何显示不同的值和出现次数?
- machine-learning - 如何使用 sample() 函数执行上采样(py-spark)
- java - 将 Shiro 与 pac4j jax-rs 实现集成
- qt - QWebEngineView显示位置
- python - 具有平均/标准偏差的python图(也许是R?)
- python - Python pyodbc 使用 SQL Server 身份验证连接到 Sql Server
- java - Spring Batch 远程分区