【问题标题】:How to sort array by date but missing out the first array item如何按日期对数组进行排序但缺少第一个数组项
【发布时间】:2019-06-18 21:17:04
【问题描述】:

我想按日期对数组进行排序。但忽略数组中的第一项。任何帮助将不胜感激。

我目前有这个:

articles.sort(function(a,b){
    return new Date(b.published) - new Date(a.published);
});

我的数组如下所示:

[
    {id: 1, published: Mar 12 2012 08:00:00 AM}, 
    {id: 2, published: Mar 9 2012 08:00:00 AM},
    {id: 3, published: Mar 15 2012 08:00:00 AM},
    {id: 4, published: Mar 22 2012 08:00:00 AM},
    {id: 5, published: Mar 8 2012 08:00:00 AM}
];

我只需要按日期从 id 2 - 5 对所有内容进行排序

我所拥有的一切。

谢谢

【问题讨论】:

  • 您的函数依赖于您提供的数组中不存在的 published 属性。请根据需要更新您的帖子。
  • 是的,谢谢我已经修改了。
  • 您想在排序后或排序前忽略数组中的第一个元素

标签: javascript arrays date object


【解决方案1】:

如果id 匹配1,您可以通过返回1Array.sort 中简单地排除id:1

let dates = [ {id: 1, published: 'Mar 12 2012 08:00:00 AM'}, {id: 2, published: 'Mar 9 2012 08:00:00 AM'}, {id: 3, published: 'Mar 15 2012 08:00:00 AM'}, {id: 4, published: 'Mar 22 2012 08:00:00 AM'}, {id: 5, published: 'Mar 8 2012 08:00:00 AM'} ];

let result = dates.sort((a,b) => 
   a.id == 1 || b.id == 1 ? 1 : new Date(a.published) - new Date(b.published))

console.log(result)

这样您就不需要concatsliceshift 任何东西。

【讨论】:

    【解决方案2】:

    使用shift() 删除第一个元素并使用unshift() 将其放回第一个位置:

    var first = articles.shift();
    articles.sort(function(a,b){
        return new Date(b.published) - new Date(a.published);
    });
    articles.unshift(first);
    

    【讨论】:

      【解决方案3】:

      要忽略数组中的第一项,sort 上的sliced 数组,然后与第一项合并。另请注意,时间戳需要是一个字符串 - 目前它是无效的。

      const articles = [{id:1,published:"Mar 12 2012 08:00:0 AM"},{id:2,published:"Mar 9 2012 08:00:0 AM"},{id:3,published:"Mar 15 2012 08:00:0 AM"},{id:4,published:"Mar 22 2012 08:00:0 AM"},{id:5,published:"Mar 8 2012 08:00:0 AM"}];
      const res = [].concat(articles[0], articles.slice(1).sort(({ published: a }, { published: b }) => new Date(a) - new Date(b)));
      console.log(res);
      .as-console-wrapper { max-height: 100% !important; top: auto; }

      【讨论】:

        【解决方案4】:

        然后,你可以移动第一行,排序后读取。

        var articles = [
            {id: 1, published: "2018-01-09"}, 
            {id: 2, published: "2019-01-01"},
            {id: 3, published: "2019-01-04"},
            {id: 4, published: "2019-01-03"},
            {id: 5, published: "2019-01-02"}
        ];
        var first = articles.shift();
        articles.sort((a, b) => {
            return new Date(b.published) - new Date(a.published);
        });
        articles.unshift(first);
        console.log(articles);

        【讨论】:

        • 你已经打败了我。我打字慢=)
        猜你喜欢
        • 2016-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-26
        • 1970-01-01
        相关资源
        最近更新 更多