Reputation: 3209
I am using laravel and it's has created_at field timestamp.
I want to sort the array of objects using the current month.
My array looks like this
var arr = [{
"id": 1,
"user_id": 1,
"roi": 90,
"sport": "Biatlon",
"created_at": "2017-12-29 11:42:40",
"user": {
"id": 1,
"userName": "iamsadek",
"profilePic": "90TyP1Rkn2WI4T5VQmqmJJPB5cAY8BMrUim1WJT0.png"
}
}, {
"id": 5,
"user_id": 2,
"roi": 30,
"sport": "Atletika",
"created_at": "2018-01-10 22:20:06",
"user": {
"id": 2,
"userName": "hkmsadek",
"profilePic": "pic.png"
}
}, {
"id": 4,
"user_id": 5,
"roi": 10,
"sport": "Biatlon",
"created_at": "2018-01-10 17:11:45",
"user": {
"id": 5,
"userName": "deil",
"profilePic": "L8KIW0gXXmi5QALnAHjksCdg4tcUK9cx5jn84nrk.jpeg"
}
}]
I want to sort this array by current month.
Please help with any clue. I am currently trying to use lodash but it doesn't provide anything like this.
Upvotes: 1
Views: 1831
Reputation: 7972
Using lodash's orderBy
method and momentjs
you could order the collection with respect to created_at
$(document).ready(function() {
var payload = [{
"id": 1,
"user_id": 1,
"roi": 90,
"sport": "Biatlon",
"created_at": "2017-12-29 11:42:40",
"user": {
"id": 1,
"userName": "iamsadek",
"profilePic": "90TyP1Rkn2WI4T5VQmqmJJPB5cAY8BMrUim1WJT0.png"
}
},
{
"id": 5,
"user_id": 2,
"roi": 30,
"sport": "Atletika",
"created_at": "2018-01-10 22:20:06",
"user": {
"id": 2,
"userName": "hkmsadek",
"profilePic": "pic.png"
}
},
{
"id": 4,
"user_id": 5,
"roi": 10,
"sport": "Biatlon",
"created_at": "2018-01-10 17:11:45",
"user": {
"id": 5,
"userName": "deil",
"profilePic": "L8KIW0gXXmi5QALnAHjksCdg4tcUK9cx5jn84nrk.jpeg"
}
}
];
var sorted = _.orderBy(payload, function(item) {
return moment(item.created_at, 'Y-M-D H:m:s').unix();
}, 'desc');
console.log(sorted);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Upvotes: 0
Reputation: 189
You can write your own compare method and call sort function from array.
function compare(a,b) {
if (a.created_at < b.created_at)
return -1;
if (a.created_at > b.created_at)
return 1;
return 0;
}
yourArray.sort(compare);
yourArray.sort(compare);
Upvotes: 1