Is there a more efficient way to sort an array based on multiple values of the same attribute in Javascript? I have the following function:
var p1 = [];
var p2 = [];
var p3 = [];
for (var i = 0; i < contentData.length; i++) {
if (contentData[i].priority === 1) {
p1.push(contentData[i]);
}
else if (contentData[i].priority === 2) {
p2.push(contentData[i]);
}
else if (contentData[i].priority === 3) {
p3.push(contentData[i]);
}
}
p1.sort(sortByDateDesc);
p2.sort(sortByDateDesc);
p3.sort(sortByDateDesc);
contentData = p1;
Array.prototype.push.apply(contentData, p2);
Array.prototype.push.apply(contentData, p3);
First I need to sort the array by its priority
attribute, and then by its date
attribute, which is done in the function sortByDateDesc
. Can this be done in a more efficient way?
Thanks!
Sample array:
var data1 = {"title": "His face looks like the best chair", "text": "So there’s this really hot kid in my creative writing class. And everyone knows I like him." +
"But one day, he walked in looking like a freaking GQ model, and I accidentally out loud whispered “Shit, his face looks like the best chair” and the girl who sits " +
"in front of me turned around and said “WTH, that’s freaky and gross” and she moved her seat." +
"She gives me weird looks every time she sees me now.", "url": "http://www.catfacts.co", "user": "Kash Muni", "timestamp": Date.now(), "read":0, "priority":2};
sortByDateDesc function:
function sortByDateDesc(a, b) {
if (a.timestamp > b.timestamp)
return -1;
if (b.timestamp > a.timestamp)
return 1;
return 0;
}