如何使用破折号对数字字符串字段进行排序

问题描述 投票:0回答:3
  sortedDatawithfield = (field, data) => {
    let res = _.sortBy(data, [field]);
    return res
  } 



  data = [
    {
      "cpm": "9.839933",
      "ctr": "8.508846",
      "cpc": "0.115644",
      "spend": "11.68",
      "date_start": "2020-03-18",
      "date_stop": "2020-03-18",
      "index": 19
    },
    {
      "cpm": "11.440139",
      "ctr": "8.849046",
      "cpc": "0.129281",
      "spend": "19.78",
      "date_start": "2020-03-17",
      "date_stop": "2020-03-17",
      "index": 18
    },
    {
      "cpm": "12.720915",
      "ctr": "8.518754",
      "cpc": "0.149328",
      "spend": "20.01",
      "date_start": "2020-03-16",
      "date_stop": "2020-03-16",
      "index": 17
    },
    {
      "cpm": "9.601182",
      "ctr": "6.351551",
      "cpc": "0.151163",
      "spend": "19.5",
      "date_start": "2020-03-22",
      "date_stop": "2020-03-22",
      "index": 21
    }
  ]


  res = this.sortedDatawithfield("cpc", data)
  console.log(res)

这里我正尝试使用lodash对“ cpc”字段进行排序。

以上是我编写的功能无法正常工作。我认为是因为它采用数字字符串格式。

有没有办法使用lodash对数字字符串进行排序

javascript lodash
3个回答
0
投票

代替lodash,您可以使用Java脚本内置的sort函数。

const data = [{
    "cpm": "9.839933",
    "ctr": "8.508846",
    "cpc": "0.115644",
    "spend": "11.68",
    "date_start": "2020-03-18",
    "date_stop": "2020-03-18",
    "index": 19
  },
  {
    "cpm": "11.440139",
    "ctr": "8.849046",
    "cpc": "0.129281",
    "spend": "19.78",
    "date_start": "2020-03-17",
    "date_stop": "2020-03-17",
    "index": 18
  },
  {
    "cpm": "12.720915",
    "ctr": "8.518754",
    "cpc": "0.149328",
    "spend": "20.01",
    "date_start": "2020-03-16",
    "date_stop": "2020-03-16",
    "index": 17
  },
  {
    "cpm": "9.601182",
    "ctr": "6.351551",
    "cpc": "0.151163",
    "spend": "19.5",
    "date_start": "2020-03-22",
    "date_stop": "2020-03-22",
    "index": 21
  }
];

const output = data.sort(({
  cpc: firstCpc,
  cpc: secondCpc
}) => Number(firstCpc) - Number(secondCpc));
console.log(output);

0
投票

您可以更改:

this.sortedDatawithfield("cpc", data)

...到:

this.sortedDatawithfield(item => parseFloat(item.cpc), data)

这应该起作用,因为_.sortBy接受选择器功能。


0
投票

您也可以通过传递如下函数来_.sortBy

_.sortBy
© www.soinside.com 2019 - 2024. All rights reserved.