如何根据react-native中的likes_count对地图数据进行排序?

时间:2018-02-12 08:44:42

标签: reactjs sorting react-native mapping

constructor(props) {
super(props);
let comments = [{body: "good", like_count: 2},
             {body: "bad article", like_count: 0}, 
             {body: "great", like_count: 4}];
this.state = { comments };
render() {
 return(
  { comments.map((comment, index) =>
   <Text>{comment.body}</Text>
  )}
 );
};

这是代码,我想按照like_count映射数据,我希望评论最多像count一样在顶部,我想打印像这样的整个评论。

如何添加此地图的条件。 我的输出将是:body:“great”,like_count:4,                     身体:“好”,like_count:2,                     body:“bad article”,like_count:0

如果有人知道,请提出解决方案,提前谢谢。

1 个答案:

答案 0 :(得分:2)

let comments = [
   {body: "good", like_count: 2},
   {body: "bad article", like_count: 0}, 
   {body: "great", like_count: 4}
];

let sortedComments = comments.sort((a, b) => a.like_count < b.like_count)

sortedComments将是:

[
   { body: 'great', like_count: 4 },
   { body: 'good', like_count: 2 },
   { body: 'bad article', like_count: 0 }
]