在节点js中对对象数组进行排序?

时间:2019-12-26 10:28:32

标签: arrays node.js sorting

我正在尝试根据publishDate中的nodejs对数组进行排序。脚本对于具有publishDate的数组可以正常工作,但是对于没有publishDate的数组会出现问题。在核心js中,所有代码都可以正常工作,但是现在当我们没有publishDate时,现在可以在节点js中工作。我请在下面查看我的代码:

代码:

const parseDate = date_string => {
    let [y,M,d,h,m,s] = date_string.split(/[- :T]/);
    return new Date(y,parseInt(M)-1,d,h,parseInt(m),s.replace('Z',''));
}

const sortByPublishDate = array => {

    array.sort(function(a, b){
        if (a.publish  && b.publish) {
            return parseDate(a.publish.publishDate) - parseDate(b.publish.publishDate)

        }
        else if (a.hasOwnProperty("publish")) {
            return -1;
        } else if (b.hasOwnProperty("publish")) {
            return 1;            
        } else {
            return 0;

        }    
    } );
    return array;
}

module.exports ={
  sortByPublishDate: sortByPublishDate
}

数组:

[
    {

        "title": "Example1",
        "publish": {

            "publishDate": "2019-8-30T12:25:47.938Z",
        }
    },   

    {

        "title": "Example2"
    },    

    {

        "title": "Example3",
        "publish": {           
            "publishDate": "2019-6-30T12:25:47.938Z",
        }
    },

    {

        "title": "Example4"
    },    

    {

        "title": "Example5",
        "publish": {           
            "publishDate": "2019-10-25T12:25:47.938Z",
        }
    }
    {

        "title": "Example6"
    }
] 

预期输出:Example3,Example1,Example5,Example2,Example4,Example6

1 个答案:

答案 0 :(得分:0)

尝试在排序之前添加对存在属性publish.publishDate的检查:

if (a.publish && a.publish.publishDate  && b.publish && b.publish.publishDate) 
{
        return parseDate(a.publish.publishDate) - parseDate(b.publish.publishDate);
}

一个例子:

let arr = [
  {
"title": "Example1",
"publish": {

  "publishDate": "2019-8-30T12:25:47.938Z",
}
  },
  {

"title": "Example2"
  },
  {
"title": "Example3",
"publish": {
  "publishDate": "2019-6-30T12:25:47.938Z",
}
  },
  {

"title": "Example4"
  },
  {
"title": "Example5",
"publish": {
  "publishDate": "2019-10-25T12:25:47.938Z",
}
  },
  {

"title": "Example6"
  }
];

const parseDate = date_string => {
  let [y, M, d, h, m, s] = date_string.split(/[- :T]/);
  return new Date(y, parseInt(M) - 1, d, h, parseInt(m), s.replace('Z', ''));
}

const sortByPublishDate = array => {

  array.sort(function (a, b) {
if (a.publish && a.publish.publishDate && b.publish && b.publish.publishDate) {
  return parseDate(a.publish.publishDate) - parseDate(b.publish.publishDate)

}
else if (a.publish) {
  return -1;
} else if (b.publish) {
  return 1;
} else {
  return 0;

}
  });
  return array;
}

console.log(sortByPublishDate(arr))