Home > Blockchain >  Javascript sort function with two conditions to be met
Javascript sort function with two conditions to be met

Time:03-26

I am want to sort messages where both important equals 1 and read equals 0 to be put at the beginning of the array.

I have an array of these message objects:

{
archived: 0
draftMode: 0
entry_date: "Mar 22, 2022"
important: 1
message: "Hello world"
messageId: 1
pinned: 0
read: 0
subject: "test"
}

The code I am using to sort is:


messages.sort((a, b) => (a.important > b.important && a.read < b.read ? -1 : 1))

CodePudding user response:

Assuming only 0 and 1 (why not use booleans?), you could take the delta of the values (works for booleans as well).

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; }

  • Related