I need to sort my js object. Nothing I have done actually works.
obj = [
{id: 1, animal: 'dog'},
{id: 2, animal: 'cat'},
{id: 3, animal: 'bird'},
{id: 4, animal: 'tiger'},
{id: 5, animal: 'snake'},
{id: 6, animal: 'gorilla'}];
My sort is below.
json['animals'][0].sort((a,b) => {
let fa = a.animal.toLowerCase();
let fb = b.animal.toLowerCase();
if(fa < fb) {
return -1;
}
if(fa> fb) {
return 1;
}
return 0;
});
The sort does not return the correct.
Will return bird,cat,dog etc others will return bird,cat,tiger,dog.etc
Where are you getting this: json['animals'][0]? Simply use obj.
const zoo=[{id:1,animal:"dog"},{id:2,animal:"cat"},{id:3,animal:"bird"},{id:4,animal:"tiger"},{id:5,animal:"snake"},{id:6,animal:"gorilla"}];
const result = zoo.sort((a, b) => a.animal < b.animal ? -1 :a.animal > b.animal ? 1 : 0);
console.log(result)