-1

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

A1exandr Belan
  • 4,442
  • 3
  • 26
  • 48
newdeveloper
  • 534
  • 3
  • 17
  • Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – Samball Mar 21 '22 at 13:23
  • 1
    Also -> `json['animals'][0]` Why only element 0?.. – Keith Mar 21 '22 at 13:24
  • 1
    Are you sure `json['animals'][0]` is the array you’ve shown? Simply do `.sort(({ animal: a, animal: b }) => a.localeCompare(b, "en", { sensitivity: "accent" }))`. See [`localeCompare`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare). – Sebastian Simon Mar 21 '22 at 13:29
  • Your code works as it should, but the `sort` function should be called for the entire array, not for an single item. In addition you can reduce size of the code `obj.sort((a, b) => a.animal.localeCompare(b.animal))` – A1exandr Belan Mar 22 '22 at 08:01

1 Answers1

0

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)
zer00ne
  • 41,936
  • 6
  • 41
  • 68