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对数字字符串进行排序
代替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);
您可以更改:
this.sortedDatawithfield("cpc", data)
...到:
this.sortedDatawithfield(item => parseFloat(item.cpc), data)
这应该起作用,因为_.sortBy
接受选择器功能。
您也可以通过传递如下函数来_.sortBy
:
_.sortBy