Last active
June 10, 2017 16:18
-
-
Save muhsin-k/59e30453334f859a95f8130b7c24fb37 to your computer and use it in GitHub Desktop.
Sort Array Object with Multiple Keys[Date and String] [Javascript ,Nodejs]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var moment = require('moment'); | |
var result = [{ | |
"rank": 1, | |
"u_total_price": 10, | |
"user": { | |
"_id": "59381ca1d48d69e140518ea3", | |
"u_firstname": "Abin", | |
"u_created_at": "2017-06-07T15:32:49.240Z" | |
} | |
}, { | |
"rank": 2, | |
"u_total_price": 9, | |
"user": { | |
"_id": "5938115e2a1b93e05a274344", | |
"u_firstname": "Muhsin", | |
"u_created_at": "2017-06-07T16:44:46.745Z" | |
} | |
}, { | |
"rank": 2, | |
"u_total_price": 9, | |
"user": { | |
"_id": "59381cafd48d69e140518ea9", | |
"u_firstname": "Shajeer", | |
"u_created_at": "2017-06-07T15:33:03.943Z" | |
} | |
}, { | |
"rank": 2, | |
"u_total_price": 9, | |
"user": { | |
"_id": "59381cdad48d69e140518eb5", | |
"u_firstname": "Safeer", | |
"u_created_at": "2017-06-07T12:33:46.332Z" | |
} | |
}, { | |
"rank": 3, | |
"u_total_price": 4, | |
"user": { | |
"_id": "59381cccd48d69e140518eaf", | |
"u_firstname": "Favas", | |
"u_created_at": "2017-06-07T15:33:32.488Z" | |
} | |
}] | |
var sorted = result.sort(function(a, b) { | |
var idDiff = b.u_total_price - a.u_total_price; | |
if (idDiff) { | |
return idDiff; | |
} | |
var aDate = moment(a.user.u_created_at); | |
var bDate = moment(b.user.u_created_at); | |
return aDate.diff(bDate, "seconds"); | |
}); | |
sorted.forEach(function(element) { | |
console.log(JSON.stringify(element)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment