【问题标题】:How can I sort this array of objects alphabetically in node js?如何在节点 js 中按字母顺序对这个对象数组进行排序?
【发布时间】:2021-01-19 12:06:20
【问题描述】:

我有一个关于如何按字母顺序排列这个对象数组的问题,我知道数组的一些元素是小写的,而其他元素有特殊字符。

数组是:

  Product { id: 1, name: 'TV Samsung MP45', price: 325.9, units: 8 },
  Product { id: 2, name: 'Ábaco de madera (nuevo modelo)', price: 245.95, units: 15 },
  Product { id: 3, name: 'impresora Epson', price: 55.9, units: 8 },
  Product { id: 4, name: 'USB Kingston 16GB', price: 5.95, units: 45 }

我必须用这个形状按字母顺序排序:

   Product { id: 2, name: 'Ábaco de madera (nuevo modelo)', price: 245.95, units: 15 },
   Product { id: 3, name: 'impresora Epson', price: 55.9, units: 8 },
   Product { id: 1, name: 'TV Samsung MP45', price: 325.9, units: 8 },
   Product { id: 4, name: 'USB Kingston 16GB', price: 5.95, units: 45 }

但结果如下:

  Product { id: 1, name: 'TV Samsung MP45', price: 325.9, units: 8 },
  Product { id: 2, name: 'Ábaco de madera (nuevo modelo)', price: 245.95, units: 15 },
  Product { id: 3, name: 'impresora Epson', price: 55.9, units: 8 },
  Product { id: 4, name: 'USB Kingston 16GB', price: 5.95, units: 45 }

为了对数组排序,我使用如下排序函数:

orderByName(){
    return this.products.sort((a,b) => a.name - b.name);
        return a.name - b.name;
}

我已经尝试了很多方法来让它与一些带有特殊字符的单词和一些小写的单词一起排序。

有人知道解决办法吗?

【问题讨论】:

标签: javascript node.js arrays sorting


【解决方案1】:

在与localeCompare 进行比较之前,您可以对这两个名称调用String#normalize

const arr = [
{ id: 1, name: 'TV Samsung MP45', price: 325.9, units: 8 },
{ id: 2, name: 'Ábaco de madera (nuevo modelo)', price: 245.95, units: 15 },
{ id: 3, name: 'impresora Epson', price: 55.9, units: 8 },
{ id: 4, name: 'USB Kingston 16GB', price: 5.95, units: 45 }
];

arr.sort((a, b) => a.name.normalize().localeCompare(b.name.normalize()));
console.log(arr);

【讨论】:

    猜你喜欢
    • 2019-06-15
    • 2017-11-23
    • 2015-01-13
    • 2012-03-31
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    相关资源
    最近更新 更多