javascript - 根据数字数组对字符串数组进行排序:另一个版本(不重复!!)
问题描述
我知道我上传了一个类似的问题,但我的意图在这里不同,所以这不是一个重复的问题。
我想根据另一个数字数组对数组进行排序。更具体地说,如果 1 是数字数组的第 n 个元素,我想重新排列目标数组,以便原始数组中的第 n 个元素是第一个元素,依此类推。例如;
//Case 1
const input = ["a", "b", "c", "d", "e"];
const order = [2, 4, 5, 1, 3];
intended_result: ["d", "a", "e", "b", "c"];
//Case 2
const input = ["a", "b", "c", "d", "e"];
const order = [3, 1, 4, 5, 2];
intended_result: ["b", "e", "a", "c", "d"];
执行上述操作的 Javascript 代码是什么?有什么建议吗?
提前非常感谢!
解决方案
无需排序,您只需要应用您拥有的排列:
const result = [];
for (let i=0; i<order; i++)
result[order[i]-1] = input[i];
推荐阅读
- vba - Excel VBA ExportAsFixedFormat 不打印边距
- web - 我可以在 Blazor 服务中调用 NavigationManager
- arrays - perl中带有哈希数组的哈希
- html - 如何根据多个条件调整此 Flexbox 布局?
- tabs - 我的 vscode 编辑器中未应用选项卡操作
- uefi - 构建 EmulatorPkg 时出现如下错误如何解决?
- spring-boot - flyway 是否支持 test 文件夹下的 sql 迁移?
- hyperledger-fabric - Hyperledger Explorer 是否与 Hyperledger Fabric v2.0.0 兼容?
- python - 错误:命令 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' 失败,退出状态为 2
- c# - vSphere VMware.Vim Clone_VM '当前状态下不允许该操作。'