Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading