混合字符串和数字(​​地址)的Lodash排序

时间:2018-08-06 06:40:37

标签: javascript lodash

let records = [
    {name: 'damilola', address: 'house 11'},
    {name: 'adeniji', address: 'House 1'},
    {name: 'segun', address: 'House 2'},
    {name: 'nathan', address: 'House 3'},
    {name: 'damilola', address: 'house 12'},
    {name: 'damilola', address: 'house12me'},
    {name: 'damilola', address: 'house11me'},
];

return _.orderBy(records, "address", "asc");

我只想用lodash方法排序

所需的输出:

[{name: 'adeniji', address: 'House 1'},
{name: 'segun', address: 'House 2'},
{name: 'nathan', address: 'House 3'},
{name: 'damilola', address: 'house 11'}
{name: 'damilola', address: 'house 12'}
{name: 'damilola', address: 'house11me'}
{name: 'damilola', address: 'house12me'}]

2 个答案:

答案 0 :(得分:2)

您可以使用string#localeCompare。要对数组进行数字排序,请使用numeric属性。

let records = [ {name: 'damilola', address: 'house 11'}, {name: 'adeniji', address: 'House 1'}, {name: 'segun', address: 'House 2'}, {name: 'nathan', address: 'House 3'}, {name: 'damilola', address: 'house 12'}, {name: 'damilola', address: 'house12me'},{name: 'damilola', address: 'house11me'}];
records.sort((a,b) => a.address.localeCompare(b.address, undefined, {numeric: true}));
console.log(records);

答案 1 :(得分:0)

也许尝试一下?

const sorted = _.orderBy(records, ["name", "address"])

此外,这是此方法的lodash文档:https://lodash.com/docs/#orderBy