最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 6浏览 0评论

对对象数组进行排序,但忽略名称中的“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);
});

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

对对象数组进行排序,但忽略名称中的“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. 暂无评论