0

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"
    }
]
Dibish
  • 9,133
  • 22
  • 64
  • 106
  • 2
    Have a look at this question about [case insensitive sorting in underscore](http://stackoverflow.com/questions/25873635/underscore-js-case-insensitive-sorting). – Gruff Bunny Jul 25 '16 at 09:59
  • 1
    `_.sortBy(connectors, o => o.name.toLowerCase());` – Tushar Jul 25 '16 at 10:00

2 Answers2

2

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

Arun AK
  • 4,353
  • 2
  • 23
  • 46
1

Why not use String#localeCompare for it?

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

connectors.sort(function (a, b) {
    return a.name.localeCompare(b.name);
});

console.log(connectors);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392