0
  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.

above is the function i have written is not working properly. I think because it is in a numeric string format .

Is there any way to sort with numeric string using lodash

1

2 Answers 2

1

You can change :

this.sortedDatawithfield("cpc", data)

...to:

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

This should work since _.sortBy accepts selector functions.

Sign up to request clarification or add additional context in comments.

Comments

0

Instead of lodash, you can use java script inbuilt 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.