-2

I have an array like below, and I need to sort the array by the string length of name field. for an example,

[
  {
    "_id": 10,
    "name": "AAAAAA"
  },
  {
    "_id": 11,
    "name": "AA"
  },
  {
    "_id": 12,
    "name": "AAAA"
  },
  {
    "_id": 13,
    "name": "A"
  },
  {
    "_id": 14,
    "name": "AAAAAAAA"
  }
]

I need the array like this,

[
  {
    "_id": 13,
    "name": "A"
  },
  {
    "_id": 11,
    "name": "AA"
  },
  {
    "_id": 12,
    "name": "AAAA"
  },
  {
    "_id": 10,
    "name": "AAAAAA"
  },
  {
    "_id": 14,
    "name": "AAAAAAAA"
  }
]

can any one help me out with this. Thanks.

Nick
  • 689
  • 14
  • 27

1 Answers1

-1

This can be accomplished with the _.orderBy method:

_.orderBy(data, [({ name }) => name.length, 'name'], ['desc']);

Here is a break-down:

I threw some "B"s into the mix to show the secondary sorting (after length is compared). Sorting the length alone is not unique enough.

const data = [
  { "_id":  1, "name": "AAAAAA"   },
  { "_id":  2, "name": "AA"       },
  { "_id":  3, "name": "AAAA"     },
  { "_id":  4, "name": "A"        }, 
  { "_id":  5, "name": "AAAAAAAA" },
  { "_id":  6, "name": "BBBBBB"   },
  { "_id":  7, "name": "BB"       },
  { "_id":  8, "name": "BBBB"     },
  { "_id":  9, "name": "B"        }, 
  { "_id": 10, "name": "BBBBBBBB" }
];

const sorted = _.orderBy(
  data,                               // Data to be sorted
  [
    ({ name: { length } }) => length, // First, sort by length
    'name'                            // Them sort lexicographically
  ], [
    'desc',                           // Length (descending)
    'asc'                             // This is implied, and could be removed
  ]
);

console.log(sorted);
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132