按字符串属性值对对象数组进行排序

4095
我有一个JavaScript对象的数组:
var objs = [ 
    { first_nom: 'Laszlo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];

如何在JavaScript中按last_nom的值对它们进行排序?
我知道sort(a,b),但似乎只适用于字符串和数字。我需要在我的对象中添加toString()方法吗?

2
大小写敏感或不敏感排序? - Peter Mortensen
61个回答

0
function compareProperty({ key, direction }) {
    return function (a, b) {
        const ap = a[key] || ''
        const bp = b[key] || ''

        return (direction === "desc" ? -1 : 1) * ((typeof ap === "string" && typeof bp === "string") ? ap.localeCompare(bp) : ap - bp)
    }
}

适用于空值、未定义的键。数字、日期、字符串、带重音符号的字符按照您的期望进行排序。

使用方法:

const sort = {
    key: "name",
    direction: "asc"
}

results.toSorted(compareProperty(sort))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接