0

I am trying to understand why the lodash orderBy function is ordering these in incorrectly. (incorrectly in my brain I suppose).

const data = [
  {
    id: '1',
    name: 'FLUoxetine (FLUoxetine 20 mg oral capsule)'
  },
  {
    id: '2',
    name: 'ascorbic acid (Vitamin C 25 mg oral tablet, chewable)'
  }
];

const orderedData = _.orderBy(data, ["name"], ["asc"]);

console.log("DATA>>>>", orderedData);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

The above code is logging out

DATAZZZZ 
[Object, Object]
0: Object
id: "1"
name: "FLUoxetine (FLUoxetine 20 mg oral capsule)"
1: Object
id: "2"
name: "ascorbic acid (Vitamin C 25 mg oral tablet, chewable)"

when I would think it would log out like so

DATAZZZZ 
[Object, Object]
0: Object
id: "2"
name: "ascorbic acid (Vitamin C 25 mg oral tablet, chewable)"
1: Object
id: "1"
name: "FLUoxetine (FLUoxetine 20 mg oral capsule)"

Can anyone explain as to why? I am assuming it has to do with the first 3 letters being capitalized. I read the lodash documentation, but I either missed something or do not fully understand it. Any help would be awesome. Thanks!

VLAZ
  • 26,331
  • 9
  • 49
  • 67
StuffedPoblano
  • 675
  • 1
  • 12
  • 35
  • 1
    It's not case-sensitive. – VLAZ Nov 26 '19 at 20:21
  • 1
    In the JS chartable, uppercase characters come before the lowercase, so `'a' < 'F' === false`, but `'A' < 'F' === true`. If you don't want to alter your object, you'll need to use your own callback. – Karl-André Gagnon Nov 26 '19 at 20:21

2 Answers2

2

Lowercase and uppercase letters have different codes, and the ones for uppercase come before lowercase. If you want case-insensitive sort, you can pass a formatter function to the orderBy as an iteratee:

const sortedData = _.orderBy(data, [data => data.name.toLowerCase()], ['asc']);
console.log(sortedData);
Clarity
  • 10,730
  • 2
  • 25
  • 35
1

It has indeed to do with the capitalisation. I suggest using the vanilla sort method, where you can make your "own" rule. Moreover, it's one less library in your project! Note that this will order the current array, and not make a copy of the existing one.

const data = [
  {
    id: '1',
    name: 'FLUoxetine (FLUoxetine 20 mg oral capsule)'
  },
  {
    id: '2',
    name: 'ascorbic acid (Vitamin C 25 mg oral tablet, chewable)'
  }
];

data.sort((a, b) => {
    const textA = a.name.toUpperCase();
    const textB = b.name.toUpperCase();
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
navelencia
  • 111
  • 1
  • 4