【问题标题】:Rearrange an arraay based on first array [duplicate]根据第一个数组重新排列数组[重复]
【发布时间】:2020-02-21 16:28:12
【问题描述】:

我有 2 个这样的数组:

array1 = ["green", "blue", "red"];
array2 = ["green", "green", "red", "red", "green", "green", "blue", "red", "Blue"];

但我需要类似的输出

output_array = ["green", "green", "green", "green", "blue", "Blue", "red", "red", "red"];

【问题讨论】:

  • 稀疏的部分呢?你试过什么?
  • 你的算法是什么?你想组合这些数组吗?您是否尝试在array1 中的方案之后对array2 进行排序?请说明。

标签: javascript arrays


【解决方案1】:

您可以将sortindexOf 一起使用:

const arr1 = ["green", "blue", "red"]
const arr2 = ["green", "green", "red", "red", "green", "green", "blue", "red", "blue"]

console.log(arr2.sort((a, b) => arr1.indexOf(a) - arr1.indexOf(b)))

【讨论】:

    【解决方案2】:

    我不知道你的意思是不是按字母顺序,但你可以合并两个数组,然后对结果进行排序:

    let output_array = array1.concat(array2);
    
    output_array.sort()
    

    【讨论】:

      【解决方案3】:

      希望这对您有所帮助!

          array1=["green","red","blue"]; 
          array2=["green","green","red","red","green","green","blue","red","Blue"];
      
          const map = array2.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());
          let result = array1.reduce((acc, a)=>  [...acc, ...Array(map.get(a)).fill(a)] , []);
          console.log(result);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-29
        • 2014-11-29
        • 2019-03-17
        • 2017-12-27
        • 1970-01-01
        • 2015-04-03
        相关资源
        最近更新 更多