首页 > 解决方案 > 如何按升序替换另一个数组中未找到的元素的值?

问题描述

let newer   = [7,8,10,0,2,3,9,24,1,4,20,19,23,5,21,6,22];

let indices_2=  [3,5,0,1,4,6,7,10,**13**,**16**,8,2,9,**14**,**15**,**11**,**12**];

Output should be = [3,5,0,1,4,6,7,10,**21**,**24**,8,2,9,**22**,**23**,**19**,**20**];

嗨,伙计们,这可能很难。如果 index_2 中的元素在 newer 中没有找到,从最小值到最大值,假设在 newer 中没有找到的第一个最小 indices_2 的数量11,它被在 index_2中没有找到的 newer 中找到的第一个最小数字替换19。然后该序列继续进行,以获取在较新版本中未找到的第二小数量的 indices_2。

let newer=[7,8,10,0,2,3,9,24,1,4,20,19,23,5,21,6,22];
  let indices_2=[3,5,0,1,4,6,7,10,13,16,8,2,9,14,15,11,12];
  let status_indices=[];  let status_indices_stat=[];
  for (let i=0;i<newer.length;i++){
    status_indices_stat="f"
    for (let f=0;f<newer.length;f++){
    if (indices_2[i]==newer[f]){
       status_indices_stat="t"
       //check whether element is found in newer.
     }

    }
    status_indices.push(status_indices_stat)
  }
  
  for (let f=0;f<newer.length;f++){
    if (status_indices[f]=="f"){
        for (let i=0;i<newer.length;i++){
         if (indices_2[f]<newer[i]){
           console.log(i)
         }
         
        }
    }
    
  }

标签: javascripthtmlarrays

解决方案


您可以用相反的方式过滤两个数组,对它们进行排序并将具有过滤索引的数组作为获取另一个过滤和排序数组的值的索引的模式。

let newer = [7, 8, 10, 0, 2, 3, 9, 24, 1, 4, 20, 19, 23, 5, 21, 6, 22],
    indices2 = [3, 5, 0, 1, 4, 6, 7, 10, 13, 16, 8, 2, 9, 14, 15, 11, 12],
    temp1 = newer.filter(v => !indices2.includes(v)).sort((a, b) => a - b),
    temp2 = indices2.filter(v => !newer.includes(v)).sort((a, b) => a - b),
    result = indices2.map(v => newer.includes(v) ? v : temp1[temp2.indexOf(v)]);

console.log(...result);


推荐阅读