最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

对对象数组进行排序,但忽略名称中的“THE”

运维笔记admin12浏览0评论

对对象数组进行排序,但忽略名称中的“THE”

对对象数组进行排序,但忽略名称中的“THE”

我有以下对象数组,

{ name: 'Hundred Monkeys',
 address: '52 High Street Glastonbury BA6 9DY' },
{ name: 'J.C Thomas and sons ltd',
 address: 'Thomas Way Glastonbury BA69LU' },
{ name: 'Lady Of The Silver Wheel',
 address: '13 Market Place Glastonbury BA6 9HH' },
{ name: 'The Chalice Well',
 address: '85-89 Chilkwell Street Glastonbury BA6 8DD' },
{ name: 'The Glastonbury Wire Studio',
 address: '48a High Street Glastonbury BA6 9DX' },
{ name: 'The Isle of Avalon Foundation',
 address: 'The Glastonbury Experience, 2-4 High Street, Glastonbury BA6 9DU' },
{ name: 'The King Arthur',
address: '31-33 Benedict Street Glastonbury BA6 9NB' },

我通过排序

VenueList.sort((a, b) => a.name.localeCompare(b.name));

但所有以'THE'开头的名字都在T下排序。我可以添加一个条件来忽略第一个单词,如果它是'The',我将如何去做?谢谢。

回答如下:

只需创建没有要在其中忽略的数据的新字符串。

然后比较那些。

VenueList.sort(function (a, b) {
    a = a.name.replace(/^The /, "");
    b = b.name.replace(/^The /, "");
    return a.localeCompare(b);
});

(根据需要调整正则表达式(例如,使其不区分大小写或添加其他单词))

发布评论

评论列表(0)

  1. 暂无评论