我有以下数组的对象,
{ 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',那我该怎么办呢?感谢。
答案 0 :(得分:6)
只需创建新的字符串,而这些字符串中没有您要忽略的数据。
然后比较那些。
VenueList.sort(function (a, b) {
a = a.name.replace(/^The /, "");
b = b.name.replace(/^The /, "");
return a.localeCompare(b);
});
(根据需要调整正则表达式(例如,使其不区分大小写或添加其他单词))
答案 1 :(得分:4)
使用decorate-sort-undecorate创建一个元组,其中包含您希望为每个对象排序的字符串。然后使用密钥排序。然后从元组中提取对象。
注意:它似乎有很多不必要的映射,但它节省了在每次比较时提取正确密钥的需要。
const VenueList = [{"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"}];
const result = VenueList
.map((o) => [o.name.replace(/^The\s+/, ''), o]) // create a tuple of ['King Arthur', {"name":"The King Arthur","address": ...}]
.sort(([a], [b]) => a.localeCompare(b))
.map(([, o]) => o); // extract the original object {"name":"The King Arthur","address": ...}
console.log(result);