首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Normalizr后进行排序

使用Normalizr后进行排序
EN

Stack Overflow用户
提问于 2017-12-18 10:44:21
回答 1查看 1.3K关注 0票数 3

在使用Normalizr之后,我有这样一个数组:

代码语言:javascript
复制
comments : {
        byId : {
            "comment1" : {
                id : "comment1",
                author : "user2",
                date: "2017-05-09 05:30:00",
                comment : "....."
            },
            "comment2" : {
                id : "comment2",
                author : "user3",
                date: "2017-04-19 04:30:00",
                comment : "....."
            },
            "comment3" : {
                id : "comment3",
                author : "user3",
                date: "2017-05-19 05:40:00",
                comment : "....."
            },
            "comment4" : {
                id : "comment4",
                author : "user1",
                date: "2017-08-06 05:30:00",
                comment : "....."
            },
            "comment5" : {
                id : "comment5",
                author : "user3",
                date: "2017-07-01 07:30:00",
                comment : "....."
            },
        },
        allIds : ["comment1", "comment2", "comment3", "commment4", "comment5"]
    },

现在,我有一个按钮可以在iddate之间更改顺序。然后,我需要将allIds (保留排序顺序)更改为按日期排序。allIds应该如下所示:

代码语言:javascript
复制
allIds : ["comment2", "comment1", "comment3", "commment5", "comment4"] // sort by date

我不知道怎么能下这个订单。我用javascript sort做了几次失败的尝试。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-18 10:55:35

您可以简单地使用Object.keys()迭代对象,然后按属性日期(解析为Date)对sort进行排序:

代码语言:javascript
复制
var comments = {
  byId: {
    "comment1": {
      id: "comment1",
      author: "user2",
      date: "2017-05-09 05:30:00",
      comment: ".....",
    },
    "comment2": {
      id: "comment2",
      author: "user3",
      date: "2017-04-19 04:30:00",
      comment: ".....",
    },
    "comment6": {
      id: "comment6",
      author: "user3",
      date: "2017-07-01 07:30:00",
      comment: ".....485",
    },
    "comment3": {
      id: "comment3",
      author: "user3",
      date: "2017-05-19 05:40:00",
      comment: ".....",
    },
    "comment4": {
      id: "comment4",
      author: "user1",
      date: "2017-08-06 05:30:00",
      comment: ".....",
    },
    "comment5": {
      id: "comment5",
      author: "user3",
      date: "2017-07-01 07:30:00",
      comment: ".....",
    },
  },
  allIds: ["comment1", "comment2", "comment3", "commment4", "comment5"]
};

var results = Object.keys(comments.byId).sort((s, a) => {
  const date1 = Date.parse(comments.byId[s].date);
  const date2 = Date.parse(comments.byId[a].date);
  
  if (date1 === date2) {
    return s.localeCompare(a);
  }
  
  return date1 - date2;
});

console.log(results);

参考文献:

注意:您忘记了date字符串后面的逗号。comment字符串后面的逗号是不必要的。

更新添加了另一个排序条件。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47866752

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档