我有以下TypeScript代码:
export const cgGroups = [
{
id: 2,
name: 'North America & Caribbean'
},
{
id: 3,
name: 'Latin America'
},
{
id: 6,
name: 'Europe'
},
{
id: 4,
name: 'Asia Pacific'
},
{
id: 1,
name: 'Middle East & Africa'
},
{
id: 7,
name: 'International'
}
];
除了一个对象
之外,我想对上面的字母进行排序{
id: 7,
name: 'International'
}
我想将它移动到排序数组的最后一个。
我尝试使用以下代码进行排序:
cgGroups = cgGroups.map(({id, name}) => ({id, name})).sort((a, b) => {
if (a.name.toLowerCase() > b.name.toLowerCase()) {
return 1;
}
if (a.name.toLowerCase() < b.name.toLowerCase()) {
return -1;
}
return 0;
});
这是预期的输出:
亚太,欧洲,拉丁美洲,中东及非洲,北美和加勒比海和国际
有人可以在这里指导我解决这个问题吗?
答案 0 :(得分:2)
它没有用,因为您没有将name: 'International'
项的条件编码到比较函数中。
可能是这样的:
cgGroups = cgGroups.map(({id, name}) => ({id, name})).sort((a, b) => {
if (a.name.toLowerCase() == 'international') {
return +1; // "a" is the greatest element of the array
} else if (b.name.toLowerCase() == 'international') {
return -1; // "a" stays before "b" because "b" is the last item
} else if (a.name.toLowerCase() > b.name.toLowerCase()) {
return 1; // regular items, compare their names
} else if (a.name.toLowerCase() < b.name.toLowerCase()) {
return -1;
}
return 0;
});
答案 1 :(得分:1)
如果您不介意向Array原型添加方法,这些是两个可能的解决方案(第一个修改原始数组,第二个返回一个新数组)。
let cgGroups = [
{
id: 2,
name: 'North America & Caribbean'
},
{
id: 3,
name: 'Latin America'
},
{
id: 6,
name: 'Europe'
},
{
id: 4,
name: 'Asia Pacific'
},
{
id: 1,
name: 'Middle East & Africa'
},
{
id: 7,
name: 'International'
}
];
const sortAlph = (a, b) => {
if (a.name.toLowerCase() > b.name.toLowerCase()) {
return 1;
}
if (a.name.toLowerCase() < b.name.toLowerCase()) {
return -1;
}
return 0;
}
Array.prototype.move = function (fromIndex, toIndex) {
let element = this[fromIndex];
this.splice(fromIndex, 1);
this.splice(toIndex, 0, element);
}
Array.prototype.moveToTheEnd = function(index) {
let element = this[index];
return this.filter(x => x !== element).concat(element);
}
cgGroups
.sort(sortAlph)
.move(cgGroups.findIndex(x => x.name === 'International'), cgGroups.length)
newArr = cgGroups
.sort(sortAlph)
.moveToTheEnd(cgGroups.findIndex(x => x.name === 'International'))
console.log(cgGroups);
console.log(newArr);