-2

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?

Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
Parth
  • 87
  • 3
  • 10
  • Just invert your 1 and -1 return values? – CertainPerformance Dec 13 '21 at 16:11
  • What doesn't work? – Bergi Dec 13 '21 at 16:12
  • Especially before the code is runnable, it would be helpful to include exactly what went wrong. Here it looks like it's just sorting it backwards, and you just needed to reverse your condition. Did you not try that? – Brian Thompson Dec 13 '21 at 16:12
  • I would've understood the minor mistake if it run properly, made a small error from my side because of which the sort function wasn't even being executed. Fixed that. – Parth Dec 13 '21 at 16:33

2 Answers2

1

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));
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
1

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

rphsantos
  • 111
  • 1
  • 4