我想對重要等于 1 和讀取等于 0 的訊息進行排序,以放在陣列的開頭。
我有一個這些訊息物件的陣列:
{
archived: 0
draftMode: 0
entry_date: "Mar 22, 2022"
important: 1
message: "Hello world"
messageId: 1
pinned: 0
read: 0
subject: "test"
}
我用來排序的代碼是:
messages.sort((a, b) => (a.important > b.important && a.read < b.read ? -1 : 1))
uj5u.com熱心網友回復:
僅假設0和1(為什么不使用布林值?),您可以取值的增量(也適用于布林值)。
const
messages = [
{ important: 0, read: 0 },
{ important: 0, read: 1 },
{ important: 1, read: 0 },
{ important: 1, read: 1 },
];
messages.sort((a, b) =>
a.read - b.read ||
b.important - a.important
);
console.log(messages);
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/452466.html
標籤:javascript 数组 排序
上一篇:用php對多維陣列進行排序
