注意目录和修改相同的字符编码

如何实现一个数组按照另外一个数组的顺序进行排序?

数组arr1按照arr2的顺序展示,如何实现:

一、简单类型数组

let arr1 = [1, 2, 3, 4, 5]
let arr2 = [5, 3, 2, 4, 1]

arr1.sort((prev,next)=>{
	return arr2.indexOf(prev)-arr2.indexOf(next)
})
console.log(arr1)       // [5, 3, 2, 4, 1] 

二、复杂类型数组

let arr1 = [ { id: 1, name: '小米' }, { id: 3, name: '小红' }, { id: 4, name: '小明' }, { id: 2, name: '小华' } ]
let arr1 = [ { id: 1, name: '小米' }, { id: 2, name: '小华' }, { id: 3, name: '小红' }, { id: 4, name: '小明' } ]

方法一:
let sortIndex = arr2.map(item => item.id) arr1.sort((a, b) => sortIndex.indexOf(a.id) - sortIndex.indexOf(b.id)) console.log(arr1)

 

方法二:
let order = new Map(twoArr.map((item, index) => [item.intID, index]));
arr1.sort((a, b) => {
	let orderA = order.has(a.id) ? order.get(a.id) : Infinity;
	let orderB = order.has(b.id) ? order.get(b.id) : Infinity;
	return orderA - orderB;
});
console.log(arr1)   
方法三:
const newArr = [];
arr2.forEach((twoE) => {
    arr1.forEach((oneE) => {
	if (twoE.id === oneE.id) {
		newArr.push(oneE);
	}
    });
});
console.log(newArr)
方法四:
const cache = {};
arr1.sort((a, b) => {
	const aId = a.id, bId = b.id;
	let aIndex = cache[aId] ?? -1;
	let bIndex = cache[bId] ?? -1;
	if (aIndex < 0 || bIndex < 0) {
		for (let i = 0; i < arr2.length; ++i) {
		       const id = arr2[i].id;
		       if (aId === id) aIndex = cache[aId] = i;
		       if (bId === id) bIndex = cache[bId] = i;
		       if (aIndex >= 0 && bIndex >= 0) break;
		 }
	}
	return aIndex - bIndex;
});
console.log(arr1)

结果:

 

posted @ 2023-09-25 18:54  黑使  阅读(478)  评论(0编辑  收藏  举报