I want to sort items after using map() function. But the sorting must be based on a specific item's property. Then how I can customize the index before I pass it to "key"?
Here the response from the API
[
{
"typeId": 2,
"count": 410
},
{
"typeId": 3,
"count": 2
},
{
"typeId": 4,
"count": 19
},
{
"typeId": 5,
"count": 21
},
{
"typeId": 6,
"count": 1
},
{
"typeId": 7,
"count": 80
}
...
]
Data exploitation
<div className="top-error-ctn">
<span className="heading">Top Errors</span>
<p>
Sorted By Type
</p>
<div className="row">
{Sometest ? (
all.slice(0, 6).map((all, index) => {
return <ErrorBar key={index} all={all} />;
})
) : (
<span>Nothing to see</span>
)}
</div>
</div>
Data Rendering
<div>
<div className="side">
<div>{all.typeId}</div>
</div>
<div className="middle">
<div className="bar-container">
<div className="bar-5"></div>
</div>
</div>
<div className="side right">
<div>{all.count}</div>
</div>
</div>
You can sort like this
all.sort(function(a, b) {
return b.count- a.count;
});
You can use Array.prototype.sort()
function like below.
const items = [ { "typeId": 2, "count": 410 }, { "typeId": 3, "count": 2 }, { "typeId": 4, "count": 19 }, { "typeId": 5, "count": 21 }, { "typeId": 6, "count": 1 }, { "typeId": 7, "count": 80 } ]; console.log('Sort by typeId:', items.sort((a, b) => a.typeId - b.typeId)); console.log('Sort by count:', items.sort((a, b) => a.count - b.count));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.