效果图:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件下载</title>
</head>
<body>
</body>
<script>
let arr = [{
id: 1,
name: "玄觞"
}, {
id: 2,
name: "叶里"
}, {
id: 6,
name: "小司"
}]
let newArr = [2, 3, 1]
// 通过order排序
function sortByOrder(arr, newArr) {
if (arr.length != newArr.length) {
console.warn("原数组和现有的数组长度不一致")
return
}
if (arr.length != Math.max(...newArr)) {
console.warn(`目标位置最大值${Math.max(...newArr)}大于原数组的长度${arr.length}`)
return
}
let order = `order_${Math.ceil(Math.random() * 1e6)}`
let data = arr.map((item, index) => {
item[order] = newArr[index]
return {
...item,
}
}).sort((a, b) => {
return a[order] - b[order]
})
data.forEach(item => {
delete item[order]
})
return data
}
console.log(sortByOrder(arr, newArr))
</script>
</html>