gpt4 book ai didi

javascript - Lodash:对对象数组进行排序,首先是字母,然后是数字

转载 作者:数据小太阳 更新时间:2023-10-29 04:33:15 24 4
gpt4 key购买 nike

我有一个对象数组,比方说:

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":"3"},{"name":"1"},{"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 - Lodash:对对象数组进行排序,首先是字母,然后是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41338449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com