首页 > 解决方案 > 根据数字数组对字符串数组进行排序:另一个版本(不重复!!)

问题描述

我知道我上传了一个类似的问题,但我的意图在这里不同,所以这不是一个重复的问题。

我想根据另一个数字数组对数组进行排序。更具体地说,如果 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 代码是什么?有什么建议吗?

提前非常感谢!

标签: javascriptarrayssorting

解决方案


无需排序,您只需要应用您拥有的排列:

const result = [];
for (let i=0; i<order; i++)
  result[order[i]-1] = input[i];

推荐阅读