Home > database >  Javascript compare function behaving differently between Firefox and Chrome
Javascript compare function behaving differently between Firefox and Chrome

Time:11-02

I'm sure I'm just missing some simple logic here and it is driving me nuts.

I'm working in Chrome v95.0.4638.69 and Firefox v93.0

I have an array of objects where the data looks like this: [ {id:1, name:"Jake", active:true}, {id:2, name:"Sam", active:false} ]

and my compare function looks like this:

let compare = (a, b) => {
    const Aname = a.name.toUpperCase();
    const Bname = b.name.toUpperCase();
    if (a.active && b.active) {
        return Aname > Bname ? 1 : Aname < Bname ? -1 : 0;
    }
    else {
        return a.active ? 1 : -1;
    }
};

What I'm trying to do is all objects with active:true should be first with name sorted alphabetically followed by objects with active:false sorted alphabetically. In Chrome it does exactly that. In Firefox objects with active = false are at the top of the list. What dumb mistake am I making?

CodePudding user response:

  1. You should sort by name when both objects have active set to the same value.
  2. When sorting by the active property, -1 should be returned if the first object has the property set to true to order it before the object with the property set to false.
  3. You don't return 0 even if the two objects should be considered equal in the else branch.
let compare = (a, b) => {
    const Aname = a.name.toUpperCase();
    const Bname = b.name.toUpperCase();
    if (a.active === b.active) {
        return Aname > Bname ? 1 : Aname < Bname ? -1 : 0;
    }
    else {
        return a.active ? -1 : b.active ? 1: 0;
    }
};
  • Related