0

I am using Coffescript, underscore.js, knockout, and I am trying to sort an array by date, but for some reason its not working

let accounts = [
  {
    id: 101,
    content: "abc1",
    createdDate: "2015-12-22T00:00:00"
  },
  {
    id: 102,
    content: "abc2",
    createdDate: "2012-12-22T00:00:00"
  }

]

This is how I wrote the code in coffeescript

_.sortBy(accounts, (a) ->  a.createdDate)

The same generated code in JS

return this.accounts(_.sortBy(accounts, function(a) {
      return a.createdDate;
    }));

Please let me know where I am going wrong. I am not getting any error, but the array is not getting sorted by date.

1 Answer 1

1

Your JSON syntax is invalid and there's no createdDate property, it should be like:

accounts = [
  {
    id: 102,
    content: "abc",
    createdDate: "2015-12-22T00:00:00"
  }
]

So you can use a function as you wrote (use => instead of ->).

Working example:

let accounts = [
  {
    id: 101,
    content: "abc1",
    createdDate: "2015-12-22T00:00:00"
  },
  {
    id: 102,
    content: "abc2",
    createdDate: "2012-12-22T00:00:00"
  },
  {
    id: 103,
    content: "abc3",
    createdDate: "2018-12-22T00:00:00"
  }
]

accounts = _.sortBy(accounts, (a) =>  a.createdDate)
console.log(accounts)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

Of course, the id and the content is just an example.

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

6 Comments

The data I gave was just an example. I am getting my data from an object, the JSon is like this { id: 101, content: "abc", createdDate: "2015-12-22T00:00:00" }
Ok, then I think the only problem is the - sign instead of the =, check the updated answer.
Yes I tried this, I put '=' instead of '-', still not working.
Please include the exact problem and error message in the question.
@Techno Are you assigning the result of sortBy back to the original array? sortBy does not mutate the original array. @Tamas is doing it in their answer, but you might have missed it: accounts = _.sortBy(accounts, (a) => a.createdDate)
|

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.