基于Javascript中相同属性的多个值对数组进行排序

Ist*_*van 1 javascript arrays sorting

有没有一种更有效的方法来根据Javascript中相同属性的多个值对数组进行排序?我有以下功能:

    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);
Run Code Online (Sandbox Code Playgroud)

首先,我需要通过其priority属性对数组进行排序,然后根据其date在函数中完成的属性对数组进行排序sortByDateDesc.这可以以更有效的方式完成吗?谢谢!

样本数组:

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};
Run Code Online (Sandbox Code Playgroud)

sortByDateDesc函数:

function sortByDateDesc(a, b) {
    if (a.timestamp > b.timestamp)
        return -1;
    if (b.timestamp > a.timestamp)
        return 1;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

tri*_*cot 6

您可以||在自定义回调函数中使用.像这样的东西:

contentData.sort( (a, b) => a.priority - b.priority || b.timestamp - a.timestamp );
Run Code Online (Sandbox Code Playgroud)

只有当a.priority - b.priority它为零(它们相等)时,才会评估表达式的第二部分,这正是您希望日期发挥作用的时间.

交换a.timestamp,b.timestamp如果日期顺序必须升序.