Home > Enterprise >  What am I doing wrong while trying to sort this array?
What am I doing wrong while trying to sort this array?

Time:12-14

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related