我有一个返回名称列表的数据数组。我想对它进行排序,以便始终在列表中首先显示特定名称(" Fav Team")。数组中有两个包含该值的字段:homeTeamName和awayTeamName。我如何对列表进行排序,以便" Fav Team"在所有其他名字之前首先显示?三元条件是正确的进程吗?
render: function() {
var gameList = this.props.data.map(function(game) {
var homeTeamName = game.home_team_name;
var homeTeamScore = game.linescore.r.home;
var awayTeamName = game.away_team_name;
var awayTeamScore = game.linescore.r.away;
var favTeam = homeTeamName || awayTeamName == "Fav Team" ? '':'';
return (
<li key={game.location} className="list-group-item">
<span className={parseInt(homeTeamScore, 10) > parseInt(awayTeamScore, 10) ? 'highlight':''}>
{homeTeamName}
<span className={'pull-right'}>{homeTeamScore}</span> <br />
</span>
<span className={parseInt(homeTeamScore, 10) < parseInt(awayTeamScore, 10) ? 'highlight':''}>
{awayTeamName}
<span className={'pull-right'}>{awayTeamScore}</span> <br />
</span>
</li>
);
});
答案 0 :(得分:0)
在呈现之前,你想要sort你的列表,所以你可以这样:
render: function() {
var gameList = this.props.data.sort(function(game) {
return (game.homeTeamName === "Fav Team" || game.awayTeamName === "Fav Team") ? -1 : 1;
}).map(function(game) {
var homeTeamName = game.home_team_name;
var homeTeamScore = game.linescore.r.home;
var awayTeamName = game.away_team_name;
var awayTeamScore = game.linescore.r.away;
return (
<li key={game.location} className="list-group-item">
<span className={parseInt(homeTeamScore, 10) > parseInt(awayTeamScore, 10) ? 'highlight':''}>
{homeTeamName}
<span className={'pull-right'}>{homeTeamScore}</span> <br />
</span>
<span className={parseInt(homeTeamScore, 10) < parseInt(awayTeamScore, 10) ? 'highlight':''}>
{awayTeamName}
<span className={'pull-right'}>{awayTeamScore}</span> <br />
</span>
</li>
);
});
}