使用ts语言写一个函数有两个输入参数对后一个数组进行排序例如:输入参数为数组a和数组b两个数组内元素都是数组a是wtxehc数组b是xtc给数组b排序期望得到返回值txc
可以使用以下代码实现:
function sortArray(a: string[], b: string[]): string[] {
// 对数组b进行排序
b.sort((x, y) => {
// 获取元素在数组a中的索引
const indexX = a.indexOf(x);
const indexY = a.indexOf(y);
// 如果元素在数组a中的索引相同,按照字母顺序排序
if (indexX === indexY) {
return x.localeCompare(y);
}
// 按照元素在数组a中的索引排序
return indexX - indexY;
});
return b;
}
// 测试
const a = ["w", "t", "x", "e", "h", "c"];
const b = ["x", "t", "c"];
console.log(sortArray(a, b)); // ["t", "x", "c"]
这段代码中,我们首先对数组b进行排序,排序的规则是先根据元素在数组a中的索引排序,如果索引相同则按照字母顺序排序。最后返回排序后的数组b
原文地址: https://www.cveoy.top/t/topic/h1rI 著作权归作者所有。请勿转载和采集!