Well I've an JavaScript array of Objects like below.
players = [{"player": "CR7", "status": false, "fullname": "Cristiano Ronaldo"},
{"player": "NJR11", "status": false, "fullname": "Neymar Jr."},
{"player": "SC11", "status": false, "fullname": "Sunil Chhetri"},
{"player": "LM10", "status": true, "fullname": "Lionel Messi"},
{"player": "SG19", "status": false, "fullname": "Sergio Aguero"}
];
Also I've used below method to sort the array. My intended result is something like Object with status is true should come first & rest of the Objects keeps the Order.
players.sort((p) => (p.status) ? -1 : 1);
It WORKS fine in Google Chrome like below.
[{"player":"LM10","status":true,"fullname":"Lionel Messi"},
{"player":"CR7","status":false,"fullname":"Cristiano Ronaldo"},
{"player":"NJR11","status":false,"fullname":"Neymar Jr."},
{"player":"SC11","status":false,"fullname":"Sunil Chhetri"},
{"player":"SG19","status":false,"fullname":"Sergio Aguero"}
]
But in Mozilla Firefox & in Android default Browser, it comes like below which is NOT I Wanted.
[{"player":"LM10","status":true,"fullname":"Lionel Messi"},
{"player":"SG19","status":false,"fullname":"Sergio Aguero"},
{"player":"SC11","status":false,"fullname":"Sunil Chhetri"},
{"player":"NJR11","status":false,"fullname":"Neymar Jr."},
{"player":"CR7","status":false,"fullname":"Cristiano Ronaldo"}
]
Why is it behaving differently in Firefox & What is the Solution to Work it just like Chrome??
You are basically shuffling the array. It shuffles the way you expect it to sort in Chrome by accident. Your sorting doesnt work at all. sort takes two elements after all, that you have to compare:
players.sort((a, b) => b.status - a.status);
That is a short form of:
players.sort((a, b) => {
if(a.status === b.status) return 0; // order doesnt matter
if(a.status) return -1; // only a has status, comes first
if(b.status) return 1 // only b has status, comes first
});
Alternatively:
players = [...players.filter(it => it.status), ...players.filter(it => !it.status)];
could be faster depending on the sort algorithm the engine uses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With