Dibish Dibish - 4 months ago 12
Javascript Question

Sort array ascending order using underscore.js

I need to sort an array in ascending order using underscore.js. Its almost working for me but issues when
sorting name contains CAPITAL letters, the capital letters name coming first in sorting order. Could you help me to fix this. Tahank you.

Tried following

connectors = [
{
"name": "ajax"
},
{
"name": "jquery"
},
{
"name": "FGJDE"
}
]
sorted = _.sortBy(connectors, 'name');


Expected output

connectors = [
{
"name": "ajax"
},
{
"name": "FGJDE"
},
{
"name": "jquery"
}
]


Am getting wrong sorting like following

connectors = [
{
"name": "FGJDE"
},
{
"name": "ajax"
},
{
"name": "jquery"
}
]

Answer

You can do like this

connectors = [{
  "name": "ajax"
}, {
  "name": "jquery"
}, {
  "name": "FGJDE"
}]
sorted = _.sortBy(connectors, function (text) { return text.name.toLowerCase(); });
console.log(sorted);

Here is the jsFiddle

Comments