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

115
Views
What am I doing wrong while trying to sort this array?

Need to sort an array of objects based on a particular value in that object.

const obj = [
    {
        field: "FULL_NAME",
        required: "Y"
    },
    {
        name: "EMAIL",
        required: "N"
    },
    {
        name: "ADDRESS",
        required: "N"
    },
    {
        name: "NUMBER",
        required: "Y"
    },
]


I want to sort this array in a way that fields with required 'Y' come first.

Tried to write a comparison function like this :

const obj = [
    {
        field: "FULL_NAME",
        required: "Y"
    },
    {
        name: "EMAIL",
        required: "N"
    },
    {
        name: "ADDRESS",
        required: "N"
    },
    {
        name: "NUMBER",
        required: "Y"
    },
];

const compare = (a, b) => {
    if(a.required === "Y" && b.required === "N"){
        return 1
    }

    if(a.required === "N" && b.required === "Y"){
        return -1
    }

    return 0;
}

console.log(obj.sort(compare));

How do I fix it so it works?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You have the 1 and -1 backwards. -1 means the first element argument is sorted first, and 1 means the second element argument is sorted first. See the compareFunction/ sort order table at the Array.prototype.sort() article:

compareFunction(a, b) return value sort order
> 0 sort b before a
< 0 sort a before b
=== 0 keep original order of a and b

const obj = [
    {
        field: "FULL_NAME",
        required: "Y"
    },
    {
        name: "EMAIL",
        required: "N"
    },
    {
        name: "ADDRESS",
        required: "N"
    },
    {
        name: "NUMBER",
        required: "Y"
    },
];

const compare = (a, b) => {
    if(a.required === "Y" && b.required !== "Y"){
        return -1
    }

    if(a.required !== "Y" && b.required === "Y"){
        return 1
    }

    return 0;
}

console.log(obj.sort(compare));

about 4 years ago · Juan Pablo Isaza Report

0

Shortest version using ES6

obj.sort((a,b) => a.required > b.required ? -1: 1);

Reference: Sort objects in an array alphabetically on one property of the array

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!