const a = [1, 2, 3];
const b = [2, 1, 4, 5, 3, 6];
// 使用filter()方法筛选出包含在数组a中的元素,并按照a数组的顺序进行排序
const sortedArray = b.filter(item => a.includes(item)).sort((x, y) => {
return a.indexOf(x) - a.indexOf(y);
});
// 将sortedArray中的元素替换掉原数组b中的元素
for (let i = 0; i < b.length; i++) {
if (a.includes(b[i])) {
b[i] = sortedArray.shift();
}
}
console.log(b); // [1, 2, 4, 5, 3, 6]
数组a=[1,2,3],数组b=[2,1,4,5,3,6]用javascript将数组b中数组a的元素按照数组a的顺序排序,其余元素顺序不变
最新推荐文章于 2024-08-03 17:05:14 发布