javascript - 如何按升序替换另一个数组中未找到的元素的值?
问题描述
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)
}
}
}
}
解决方案
您可以用相反的方式过滤两个数组,对它们进行排序并将具有过滤索引的数组作为获取另一个过滤和排序数组的值的索引的模式。
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);
推荐阅读
- influxdb - 如何根据测量名称将数据写入不同的数据库
- c# - 在 LINQ 中将 DateTime 与毫秒进行比较
- r - 在 R markdown 输出中将图形标题分配给 html 小部件(vtree 包)
- vue.js - Keycloak 错误:代码无效 - 用于客户端令牌请求
- mongodb - 如何在 MongoDB Atlas 和 Google App Engine 标准环境节点应用程序之间建立对等互连
- java - LayoutManager 用于不同大小的组件,无需编码绝对位置
- git - AppData\Local\Programs\Microsoft' 未被识别为内部或外部命令
- javascript - 从输入数据中绘制 svg 矩形
- r - 带有 if 条件的包装函数
- swift - Cocoa:将 NSView 掩码设置为 CAShapeLayer