我有一个对象列表,我希望基于类型字符串的字段attr进行排序。我试着用

list.sort(function (a, b) {
    return a.attr - b.attr
})

但发现-似乎不适用于JavaScript中的字符串。我如何能排序基于类型字符串的属性的对象列表?


当前回答

嵌套三元箭头函数

(a,b) => (a < b ? -1 : a > b ? 1 : 0)

其他回答

在javascript中,我们使用.localCompare方法对字符串进行排序

为打印稿

const data = ["jane", "mike", "salome", "ababus", "buisa", "dennis"];

const sort = (arr: string[], mode?: 'desc' | 'asc') => 
  !mode || mode === "asc"
    ? arr.sort((a, b) => a.localeCompare(b))
    : arr.sort((a, b) => b.localeCompare(a));


console.log(sort(data, 'desc'));// [ 'salome', 'mike', 'jane', 'dennis', 'buisa', 'ababus' ]
console.log(sort(data, 'asc')); // [ 'ababus', 'buisa', 'dennis', 'jane', 'mike', 'salome' ]


对JS

const data = ["jane", "mike", "salome", "ababus", "buisa", "dennis"];

/**
 * @param {string[]} arr
 * @param {"asc"|"desc"} mode
 */
const sort = (arr, mode = "asc") =>
  !mode || mode === "asc"
    ? arr.sort((a, b) => a.localeCompare(b))
    : arr.sort((a, b) => b.localeCompare(a));

console.log(sort(data, 'desc'));// [ 'salome', 'mike', 'jane', 'dennis', 'buisa', 'ababus' ]
console.log(sort(data, 'asc')); // [ 'ababus', 'buisa', 'dennis', 'jane', 'mike', 'salome' ]

这里应该使用>或<和==。所以解决方案是:

list.sort(function(item1, item2) {
    var val1 = item1.attr,
        val2 = item2.attr;
    if (val1 == val2) return 0;
    if (val1 > val2) return 1;
    if (val1 < val2) return -1;
});

在第一个问题的操作中,您正在执行以下操作:

item1.attr - item2.attr

所以,假设这些是数字(即item1。Attr = "1", item2。attr =" 2")您仍然可以使用"==="运算符(或其他严格求值符),只要您确保类型。以下方法应该有效:

return parseInt(item1.attr) - parseInt(item2.attr);

如果它们是字母和数字,那么使用localCompare()。

为什么问题中的方法不起作用的解释:

let products = [
    { name: "laptop", price: 800 },
    { name: "phone", price:200},
    { name: "tv", price: 1200}
];
products.sort( (a, b) => {
    {let value= a.name - b.name; console.log(value); return value}
});

> 2 NaN

字符串之间的减法返回NaN。

附和@Alejadro的回答,正确的方法是——

产品。排序(a,b) => a。一、二、三)

应该有升序和降序函数

if (order === 'asc') {
  return a.localeCompare(b);
}
return b.localeCompare(a);