假设我们有两个像这样的数组-
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' ]