对对象数组进行排序,但忽略名称中的“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);
});
(根据需要调整正则表达式(例如,使其不区分大小写或添加其他单词))