【问题标题】:How to sort an array by an array of integers in JS? [duplicate]如何在JS中通过整数数组对数组进行排序? [复制]
【发布时间】:2021-04-30 05:03:43
【问题描述】:

请您帮忙转换一下这个数组:

['John', 'Paul', 'George', 'Ringo'] 

使用这个数组:

[3, 1, 2, 0]

到这里:

['Ringo', 'Paul', 'George', 'John']

谢谢一百万!

【问题讨论】:

  • 你可以用很多不同的方式来做(有些比其他的更明智);你可以在这里看到一些例子:jsfiddle.net/fusnaz2x

标签: javascript arrays reactjs sorting


【解决方案1】:

您可以使用.map() 将索引数组映射到名称数组中的相应值:

const names = ['John', 'Paul', 'George', 'Ringo'] 
const nums = [3, 1, 2, 0];
const res = nums.map(i => names[i]);
console.log(res);

【讨论】:

    【解决方案2】:

    您可以遍历这两个数组并将其存储到一个新数组中。

    var x = [];
    var arr = ["John", "Paul", "George", "Ringo"];
    var arr2 = [3, 1, 2, 0];
    for(var i = 0; i < arr.length; i++){
        var val = arr2[i];
        x[val] = arr[i];
    }
    //"x" has your finalized array.
    

    【讨论】:

      【解决方案3】:

      "项目编号项目编号索引"

      const intArray = [3, 1, 2, 0];
      // "arr" is the name of the array of names.
      let arr = ["John", "Paul", "George", "Ringo"];
      arr = arr.map((el, ind) => arr[intArray[ind]]);
      
      console.log(arr);

      【讨论】:

        【解决方案4】:

        使用array.proto.forEach

        const arr = ["a", "b", "c", "d"];
        const order = [4, 3, 2, 1];
        const newArr = []
        order.forEach(item=>{
            newArr.push(arr[item-1]);
            //minus 1 because 4th item is actually [3] index
        });
        console.log(newArr);

        【讨论】:

          【解决方案5】:
          const arr1 = ["John", "Paul", "George", "Ringo"];
          const arr2 = [3, 1, 2, 0];
          const newArr = new Array(arr1.length).fill(0); // Creating an array in the size of arr1 with all values set to 0
          
          arr1.forEach((el ,i) => { // Iterating over arr1 and getting the current element and its index
            newArr[arr2[i]] = el; // Placing the current element in the needed index in the new array (arr2[i] is the needed index from arr2)
          })
          

          【讨论】:

          • 请解释为什么这会起作用以及 OP 做错了什么/正确。这将对他们和任何其他读者有所帮助。