在 JavaScript 中根据另一个数组对一个数组进行排序
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/24 8:12:17
假设我们有两个像这样的文字数组 −
const arr1 = [1, 3, 2, 4, 5, 6]; const arr2 = [1, 2, 5];
我们需要编写一个接受两个这样的数组的 JavaScript 函数。然后我们的函数应该返回一个包含 arr1 的所有元素但根据 arr2 排序的新数组。
就像出现在两个数组中的元素一样,它们应该首先按照它们在第二个数组中的顺序出现,然后是仅存在于第一个数组中的元素,并保持它们的顺序。
示例
其代码为 −
const arr1 = [1, 3, 2, 4, 5, 6];
const arr2 = [1, 2, 5];
const sortByReference = (arr1, arr2) => {
const inBoth = el => arr1.indexOf(el) !== -1 && arr2.indexOf(el) !== -1;
const sorter = (a, b) => {
if(inBoth(a) && inBoth(b)){
return arr1.indexOf(a) - arr2.indexOf(b);
}
if(inBoth(a)){
return -1;
};
if(inBoth(b)){
return 1;
};
return 0;
};
arr1.sort(sorter);
};
sortByReference(arr1, arr2);
console.log(arr1);
输出
控制台中的输出 −
[ 1, 2, 5, 3, 4, 6 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

