javascript – Lodash:排序对象数组,首先排列字母,然后是数字

前端之家收集整理的这篇文章主要介绍了javascript – Lodash:排序对象数组,首先排列字母,然后是数字前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个对象数组,让我们说:
var objects = [
  {name: 'A'},{name: '1'},{name: 'B'}
]

知道我可以使用Lodash sortBy对其进行排序:

objects= _.sortBy(objects,'name')

这将导致:

[
  {name: '1'},{name: 'A'},{name: 'B'}
]

但我想要的输出是这样的:

[
  {name: 'A'},{name: 'B'},{name: '1'}
]

请帮忙.

解决方法

使用Array#sort您可以应用此逻辑:
// If both are numbers or both are not numbers
isNaN(a.name) === isNaN(b.name) ?
     // then compare between them 
    a.name.localeCompare(b.name)
    : // else
    // If the 1st is not a number move it up,if it's a number move it down
    (isNaN(a.name) ? -1 : 1);

没有lodash:

var objects = [{"name":"A"},{"name":"3"},{"name":"1"},{"name":"B"}];

objects.sort(function(a,b) {
  return isNaN(a.name) === isNaN(b.name) ? a.name.localeCompare(b.name) : (isNaN(a.name) ? -1 : 1);
});

console.log(objects);

作为lodash链的一部分:

var objects = [{"name":"A"},{"name":"B"}];

var result = _(objects)
  .sort(function(a,b) {
    return isNaN(a.name) === isNaN(b.name) ? a.name.localeCompare(b.name) : (isNaN(a.name) ? -1 : 1);
  }) 
  .value();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.3/lodash.min.js"></script>

猜你在找的JavaScript相关文章