Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
Failing to sort js object by value

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!