Home > Blockchain >  How to customize sort an array
How to customize sort an array

Time:07-11

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!

CodePudding user response:

.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);

CodePudding user response:

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)

  • Related