简体   繁体   English

如何使用 lodash 对数字字符串字段进行排序

[英]How to sort a numeric string field with lodash

  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)

Here i am trying to sort "cpc" field using lodash.在这里,我尝试使用 lodash 对“cpc”字段进行排序。

above is the function i have written is not working properly.以上是我写的 function 不能正常工作。 I think because it is in a numeric string format.我认为是因为它是数字字符串格式。

Is there any way to sort with numeric string using lodash有没有办法使用 lodash 对数字字符串进行排序

You can change:你可以改变:

this.sortedDatawithfield("cpc", data)

...to: ...至:

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

This should work since _.sortBy accepts selector functions.这应该可以工作,因为_.sortBy接受选择器函数。

Instead of lodash , you can use java script inbuilt sort function.代替lodash ,您可以使用 java 脚本内置sort function。

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM