Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
Javascript sort function with two conditions to be met

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))
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!