【问题标题】:Sort one array the same way as another array JavaScript以与另一个数组 JavaScript 相同的方式对一个数组进行排序
【发布时间】:2020-01-05 15:47:18
【问题描述】:

我有 2 个数组:

[2, 4, -2, 4, 1, 3]
["a", "b", "c", "d", "e", "f"]

我希望它们按数字数组排序:

// output
[-2, 1, 2, 3, 4, 4] // <-sorted by numerical order
["c", "e", "a", "f", "b", "d"] // sorted exactly the same order as the first array

虽然“b”或“d”先出现实际上并不重要(在此示例中它们都有 4)

我在网上找到了很多关于此的问题,但没有一个对我有用,谁能帮我解决这个问题?

【问题讨论】:

  • 数组可以有不同的长度吗?那么如何处理呢?

标签: javascript arrays sorting


【解决方案1】:

您可以根据值对第一个数组的keys 进行排序。这将返回一个数组,该数组的索引根据numbers 数组的值排序。然后使用map根据索引获取排序后的值

const numbers = [2, 4, -2, 4, 1, 3],
      alphabets = ["a", "b", "c", "d", "e", "f"]

const keys = Array.from(numbers.keys()).sort((a, b) => numbers[a] - numbers[b])

const sortedNumbers = keys.map(i => numbers[i]),
      sortedAlphabets = keys.map(i => alphabets[i])

console.log(
  sortedNumbers,
  sortedAlphabets
)

【讨论】:

    【解决方案2】:

    一种标准方法是获取键数组的索引进行排序,然后通过获取键数组中的索引和值,将索引作为所有其他数组的模式进行排序。

    最后映射排序的数组。

    var array1 = [2, 4, -2, 4, 1, 3],
        array2 = ["a", "b", "c", "d", "e", "f"],
        indices = [...array1.keys()].sort((a, b) => array1[a] - array1[b]);
    
    [array1, array2] = [array1, array2].map(a => indices.map(i => a[i]));
    
    console.log(...array1);
    console.log(...array2);

    【讨论】:

      【解决方案3】:

      我建议将整个内容存储在地图中。这样,您可以根据需要对第一个数组进行独立排序,然后使用这些值作为键来调用第二个数组的相应值。

      【讨论】:

        【解决方案4】:

        您可以通过关联两个数组然后对项目进行排序来在一行中完成此操作:

        const x = ["a", "b", "c", "d", "e", "f"]   
        const y = [2, 4, -2, 4, 1, 3]
        
        const result = y.map((val, index)=>({x:x[index], y:val})).sort((a,b)=>a.y-b.y).map(v=>v.x)
        
        // -> ["c", "e", "a", "f", "b", "d"]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-05
          • 1970-01-01
          • 2016-07-12
          • 1970-01-01
          • 2020-09-27
          • 2019-06-24
          相关资源
          最近更新 更多