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

126
Views
How to customize sort an array

I'm trying to sort an array of objects in JS, but for some reason it doesnt work.

This is the code I'm running:

    let myArr = [{ "title": "AA" }, { "title": "ABC" }, { "title": "Ac" }, { "title": "adidas" }, { "title": "Ba" }, { "title": "BB" }]
    let sortList = myArr.sort(function (a, b) {
        const titleA = (a.title || '').substring(0, 1).toLowerCase();
        const titleB = (b.title || '').substring(0, 1).toLowerCase();
        return titleA > titleB ? 1 : -1;
    })
    console.log(sortList)

Output I am getting :

[
{
    "title": "adidas"
},
{
    "title": "Ac"
},
{
    "title": "ABC"
},
{
    "title": "AA"
},
{
    "title": "BB"
},
{
    "title": "Ba"
}

]

I actually wanted output as below:

  1. sort a after A

  2. sort B after A

  3. sort Ac after ABC

     [
         {
             "title": "AA"
         },
         {
             "title": "ABC"
         },
    
         {
             "title": "Ac"
         },
         {
             "title": "adidas"
         },
    
         {
             "title": "Ba"
         },
    
         {
             "title": "BB"
         }
     ]
    

Any idea what I did wrong? Thanks in advance for any help!

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

0

.sort() and .localeCompare(). Note, in the OP, the input array is already sorted correctly so in this answer I have jumbled the order of the input array to demonstrate that the code functions correctly.

const data = [{ "title": "BB" }, { "title": "Ac" }, { "title": "adidas" }, { "title": "AA" }, { "title": "Ba" }, { "title": "ABC" }];

const output = data.sort((a, b) => a.title.localeCompare(b.title));

console.log(output);

about 4 years ago · Juan Pablo Isaza Report

0

You just need to sort it on lower case.

    let myArr = [{ "title": "AA" }, { "title": "ABC" }, { "title": "Ac" }, { "title": "adidas" }, { "title": "Ba" }, { "title": "BB" }]
    let sortList = myArr.sort(function (a, b) {
        return a.title.toLowerCase() > b.title.toLowerCase()
    })
    console.log(sortList)

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!