【问题标题】:Arrange array based on another array Javascript基于另一个数组Javascript排列数组
【发布时间】:2019-05-02 05:05:54
【问题描述】:

我有一个参考数组,它的值是["a","b","c","d"]。我还有另一个数组作为 API 的一部分获得,它的格式不是很一致。我在下面指出一些例子

case 1.`{
     names : ["a"],
     value : [ [0],[0],[2],[4],... ]
   }`
case 2. `{
     names : ["a","c"],
     value : [ [0,2],[0,0],[2,3],[4,4],... ]
    }`

结果可以是任意组合 但我的要求是将传入结果的值分配到另一个数组中 索引与我的参考数组相同 例如:在 案例一

`
let finalArray = [["0",null,null,null],
                  ["0",null,null,null], 
                   ["2",null,null,null]....  ]
`

对于案例 2:

`let finalArray = [["0",null,"2",null],
                  ["0",null,"0",null], 
                   ["2",null,"3",null]....   ]  
`

还附上我在下面的输入的小提琴

jsfiddle link to problem

有什么建议吗? 我正在尝试使用最少的 for 循环进行性能优化

【问题讨论】:

  • 你有没有尝试过实现这个目标?请发布您尝试过的内容
  • 如果有人想知道,我认为a, b, c, d 表示“值”数组的位置0, 1, 2, 3
  • 不清楚(至少对我而言)您想要的结果与您开始的内容有何关系。
  • 对不起,我的解决方案也更新了我的小提琴,但正如我之前所说,这不是一个好的解决方案,因为我在数组中有成千上万个条目。 @CertainPerformance,@MarkMeyer

标签: javascript jquery arrays node.js ecmascript-6


【解决方案1】:

希望这会有所帮助。

var refArray = ["a","b","c","d"];

setTimeout(()=>{processResult({
     "names" : ["a"],
     "value" : [ [0],[0],[2],[4]]
   })},2000);
setTimeout(()=>{processResult(
{
     "names" : ["a","c"],
     "value" : [ [0,2],[0,0],[2,3],[4,4]]
})},4000);
setTimeout(()=>{processResult(
{
     "names" : ["d","c"],
     "value" : [ [0,2],[0,0],[2,3],[4,4]]
})},6000);


function processResult (result) {
    let res = result.value;
    let resArray = res.map((el)=>{
        let k=Array(refArray.length).fill(null);
        refArray.forEach((e,i)=>{
          let indx = result.names.indexOf(e);
          if(indx>=0){      	
                k[i] = el[indx]
            }      
        });
        return k;
    })
  console.log("result",resArray)	
}

【讨论】:

    【解决方案2】:

    以下是我能想到的需要最少迭代次数的内容。

        var refArray = ["a", "b", "c", "d"];
        setTimeout(()=>{processResult({
             "names" : ["a"],
             "value" : [ [0],[0],[2],[4]]
           })},2000);
        setTimeout(()=>{processResult(
        {
             "names" : ["a","c"],
             "value" : [ [0,2],[0,0],[2,3],[4,4]]
        })},4000);
        setTimeout(()=>{processResult(
        {
             "names" : ["d","c"],
             "value" : [ [0,2],[0,0],[2,3],[4,4]]
        })},6000);
    
    
        function processResult(result) {
          //This map will contain max names matched in the result
          var maxItemsFromResult = {};
    
          //Find the indexes in refArray and fill map
          //e.g. 1st- {0:0}, 2nd - {0:0, 1:2}, 3rd - {0:3, 1:2}
          result.names.forEach((item, index) => {
            let indexFound = refArray.indexOf(item);
            if (indexFound > -1) {
              maxItemsFromResult[index] = indexFound;
            }
          });
    
          //for performance if no key matched exit
          if (Object.keys(maxItemsFromResult).length < 1) {
            return;
          }
          //This will be final result
          let finalArray = [];
    
          //Because finalArray's length shuld be total items in value array loop through it
          result.value.forEach((item, itemIndex) => {
            //Create a row
            let valueArray = new Array(refArray.length).fill(null);
            //Below will only loop matched keys and fill respective position/column in row
            //i'm taking all the matched keys from current value[] before moving to next
            Object.keys(maxItemsFromResult).forEach((key, index) => {
              valueArray[maxItemsFromResult[key]] = item[index];//get item from matched key
            });
            finalArray.push(valueArray);
          });
          console.log(finalArray);
          return finalArray;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 2013-06-24
      • 1970-01-01
      • 2014-10-25
      • 2017-06-24
      • 1970-01-01
      相关资源
      最近更新 更多