排序数组给出错误的结果

时间:2019-01-08 11:06:33

标签: javascript arrays sorting

我有一个对象数组:

[{ date: '2018 49th', '3_SLS93 N/P': 1582.86, '320_Oleic Acid 75 min': 825 },
{ date: '2018 50th', '3_SLS93 N/P': 1572.14, '320_Oleic Acid 75 min': 825 },
{
  date: '2018 51st',
  '3_SLS93 N/P': 1582.86,
  '320_Oleic Acid 75 min': 828.57,
},
{
  date: '2018 52nd',
  '3_SLS93 N/P': 1562.14,
  '320_Oleic Acid 75 min': 835.71,
},
{ date: '2019 1st', '3_SLS93 N/P': 1555, '320_Oleic Acid 75 min': 833.33 },
{ date: '2017 48th', '3_SLS93 N/P': 1560.0, '320_Oleic Acid 75 min': 1255 }];

我想基于date值升序排列,因此结果将如下所示:

[{ date: '2017 48th', '3_SLS93 N/P': 1560.0, '320_Oleic Acid 75 min': 1255 }, { date: '2018 49th', '3_SLS93 N/P': 1582.86, '320_Oleic Acid 75 min': 825 },
    { date: '2018 50th', '3_SLS93 N/P': 1572.14, '320_Oleic Acid 75 min': 825 },
    {
      date: '2018 51st',
      '3_SLS93 N/P': 1582.86,
      '320_Oleic Acid 75 min': 828.57,
    },
    {
      date: '2018 52nd',
      '3_SLS93 N/P': 1562.14,
      '320_Oleic Acid 75 min': 835.71,
    },
    { date: '2019 1st', '3_SLS93 N/P': 1555, '320_Oleic Acid 75 min': 833.33 }];

我仅使用sort(),但它没有变化。

1 个答案:

答案 0 :(得分:5)

您可以使用自定义排序功能,如下所示:

var array = [{ date: '2018 49th', '3_SLS93 N/P': 1582.86, '320_Oleic Acid 75 min': 825 },
{ date: '2018 50th', '3_SLS93 N/P': 1572.14, '320_Oleic Acid 75 min': 825 },
{
  date: '2018 51st',
  '3_SLS93 N/P': 1582.86,
  '320_Oleic Acid 75 min': 828.57,
},
{
  date: '2018 52nd',
  '3_SLS93 N/P': 1562.14,
  '320_Oleic Acid 75 min': 835.71,
},
{ date: '2019 1st', '3_SLS93 N/P': 1555, '320_Oleic Acid 75 min': 833.33 },
{ date: '2017 48th', '3_SLS93 N/P': 1560.0, '320_Oleic Acid 75 min': 1255 }];

sorted_array = array.sort((a, b) => {
  if (a.date < b.date) {
    return -1;
  }
  if (a.date > b.date) {
    return 1;
  }
  return 0;
});

console.log(sorted_array);

如果您更喜欢短代码,这里也是一个较短的版本:

var array = [{ date: '2018 49th', '3_SLS93 N/P': 1582.86, '320_Oleic Acid 75 min': 825 },
{ date: '2018 50th', '3_SLS93 N/P': 1572.14, '320_Oleic Acid 75 min': 825 },
{
  date: '2018 51st',
  '3_SLS93 N/P': 1582.86,
  '320_Oleic Acid 75 min': 828.57,
},
{
  date: '2018 52nd',
  '3_SLS93 N/P': 1562.14,
  '320_Oleic Acid 75 min': 835.71,
},
{ date: '2019 1st', '3_SLS93 N/P': 1555, '320_Oleic Acid 75 min': 833.33 },
{ date: '2017 48th', '3_SLS93 N/P': 1560.0, '320_Oleic Acid 75 min': 1255 }];

sorted_array = array.sort((a, b) => (a.date > b.date) - (a.date < b.date));

console.log(sorted_array);