Hii sir i have some doubt in array sort

here i have done sort with two different ways in second i am getting output correctly but in second one why i am not getting where i am doing wrong

var mObj = [{
    name: 'John', 
    score: 98
    },{
    name: 'Alice',
    score: 99
    },{
    name: 'Johnathan',
    score: 90
    }]

2.function sortName(a,b){
let name1 = a.name.toUpperCase()
let name2 = b.name.toUpperCase()
return name1 -name2
}
console.log(mObj.sort(sortName))
//output -:
[
{ name: ‘John’, score: 98 },
{ name: ‘Alice’, score: 99 },
{ name: ‘Johnathan’, score: 90 }
]

  1. function sortName1(a,b){
    name1 = a.name.toLowerCase()
    name2 = b.name.toLowerCase()
    if(name1<name2){
    return -1
    }
    else if(name1>name2){
    return 1
    }
    return 0
    }

console.log( mObj.sort(sortName1),“sort1”)
// output-: [
{ name: ‘Alice’, score: 99 },
{ name: ‘John’, score: 98 },
{ name: ‘Johnathan’, score: 90 }
] sort1

Hi @utkarshshahi015 , thank you for sharing your query with us. We are working on providing the best resolution to this query and will share it soon here.

In if block try name1.length>name2.length as if block only takes boolean values

1 Like