javascript - 显示列表中的最高分
问题描述
我有一个数组this.state
。数组的对象有 2 个键:[text] 和 [score]。
我只需要显示得分最高的对象的 [text] 键。例如
[{ text: 'foo', score: 1, }, { text: 'bar', score: 0.1, }]
这里最高分是 1,[text] 键值为“foo”。所以只需渲染“foo”。
代码:
class Score extends React.Component {
constructor(props) {
super(props);
this.state =
{
text: [
{
title: 'el',
data: [
{
el: 'hello',
score: 1
},
{
el: 'hallo',
score: 0.10
}
]
},
]
}
}
render() {
return (
<div>
{
this.state.text.map((q, i) => (
<div key={i} className="card">
{
q.data.map((i, j) =>
(
<div key={j}>
<p>{i.el}</p>
<p>{i.score}</p>
</div>
)
)}
</div>
))
}
</div>
);
}
}
const Root = document.getElementById("root");
ReactDOM.render(<Score />, Root);
解决方案
Array#map
将显示每个元素,而不仅仅是得分最高的元素。
在地图内部,您应该删除一些逻辑,该逻辑将找到得分最高的对象并显示它。
this.state.text.map((q, i) => {
const r = q.data.sort((a, b) => b.score - a.score)[0];
// ^^^^^^^^^^^^^^^^^^^ sort ascending and pick the first element
return (
<div key={i} className="card">
<p>{r.el}</p>
<p>{r.score}</p>
</div>
);
})
const r = [{ text: 'hello', score: 1 }, { text: 'hallo', score: 0.1 }];
const res = r.sort((a, b) => b.score - a.score)[0];
console.log(res);
推荐阅读
- kubernetes - kops 导出 kubeconfig,TTL 不会减少
- dataset - 如何在 SSRS 中添加 2 个数据集
- php - 如何使用 PHP 过滤 REST API 中的响应?
- chart.js - 如何在chartjs或ng2-chart的箱形图中使用时间?
- reactjs - 在没有后端的情况下实现 google-recaptcha v3
- flutter - 是否可以将我的颤振应用程序设置为打开特定类型文件的默认操作?
- xml - AAPT:错误:“techport”与属性 layout_constraintStart_toEndOf (attr) 参考不兼容|枚举 [parent=0]
- javascript - 如何在 JavaScript 中按频率排序然后过滤重复 - 解决方案
- java - java.util.localdate 遇到问题
- javascript - jquery if 小时和分钟 <>