elixr_elixir 列表排序的例子

时间:2020-11-14  来源:英文短信  阅读:

在 elixir 里,我有个列表,大概是这样:

  [
    %{id: 1, retweet_count: 10, favorite_count: 20},
    %{id: 2, retweet_count: 20, favorite_count: 1},
    %{id: 3, retweet_count: 15, favorite_count: 50},
  ]
现在想按 retweet_count 与 favorite_count 的总数降序排列。

在 JavaScript 里,这非常简单:

  list.sort(function (a, b) {
    if (a.retweet_count + a.favorite_count > b.retweet_count + b.favorite_count) {
      return -1
    } else if (a.retweet_count + a.favorite_count < b.retweet_count + b.favorite_count) {
      return 1
    }
    return 0
  })
Elixir 有个类似的方法 sort_by:

sort(enumerable, fun)

于是我们的降序排列规则写成如下:

 Enum.sort [
    %{id: 1, retweet_count: 10, favorite_count: 20},
    %{id: 2, retweet_count: 20, favorite_count: 1},
    %{id: 3, retweet_count: 15, favorite_count: 50},
  ], &(Map.get(&1, :retweet_count) + Map.get(&1, :favorite_count) >= Map.get(&2, :retweet_count) + Map.get(&2, :favorite_count))

elixr_elixir 列表排序的例子

http://m.bbyears.com/zhufuduanxin/110508.html

推荐访问:雷霄骅 类型 类星体 泪腺 缧绁 类型片 雷姓 雷小屈
相关阅读 猜你喜欢
本类排行 本类最新