基于另一个数组 JavaScript 对数组进行排序
javascriptweb developmentfront end technologyobject oriented programming
假设我们有两个像这样的数组 −
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' ]