基于另一个数组JavaScript对数组进行排序
假设我们有两个像这样的数组-
const input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8']; const sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"];
我们需要编写一个JavaScript函数,该函数分别采用两个这样的数组作为第一个和第二个参数。
函数应根据它们在第二个数组中的位置对第一个数组的元素进行排序。
为此的代码将是-
示例
const input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8'];
const sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"];
const sortByReference = (arr1 = [], arr2 = []) => {
const sorter = (a, b) => {
const firstIndex = arr2.indexOf(a);
const secondIndex = arr2.indexOf(b);
return firstIndex - secondIndex;
};
arr1.sort(sorter);
};
sortByReference(input, sortingArray); console.log(input);输出结果
控制台中的输出将是-
[ 'S-1', 'S-5', 'S-2', 'S-6', 'S-3', 'S-7', 'S-4', 'S-8' ]
热门推荐
10 生日祝福语朋友简短的话
11 宝贝的人生祝福语简短
12 新年有哪些祝福语简短
13 简短又洋气祝福语大全
14 简短祝福语除夕快乐英文
15 生日贺卡祝福语毕业简短
16 战友聚会祝福语幽默简短
17 最新中秋祝福语简短英语
18 夏日升学宴祝福语简短