所以我对编码非常陌生,在比较数组时遇到了问题,特别是那些嵌套的数组并试图使用它们的索引将匹配的值提取到新数组中。假设我在示例中有两个不同的数组,其中一个是嵌套数组:
const array1 = [1,2,3,4,5,6,7,8,9,10]
const array2 =
[
[1,2,4,6]
[1,3,7,9,10]
[1,2]
[1,6,8,9]
]
我需要嵌套数组根据原始数组检查每个值,看看它是否匹配,如果匹配,则将该值拉入同一索引处的新数组中。如果它在该索引处不匹配,那么我需要它惰性化分隔符或某种空白值,然后完成其余值与两个数组的比较。我还需要新的输出数组与原始数组的长度相同,因此上述值的预期输出为:
const ouputtedArray =
[
[1,2,,4,,6,,,,,]
[1,,3,,,,7,,9,10]
[1,2,,,,,,,,,]
[1,,,,,6,,8,9,]
]
I have tried a couple of different approaches and spent hours online looking for the answer with no hope. For example I have tried to compare the two arrays using a for loop:
for(let i = 0; i <=array1.length;i++){
if( i + array2[0][i] == i + array1[i]){
const match = i + array2[0][i]
const arrays =[]
console.log([match])
}}
//console.log output
['1']
['2']
整个过程的最终目标是能够将这些数据输入到电子表格中,因此我需要保留空白来表示 CSV 格式中的空单元格,因此最终总体数据将是:
const array1 = [1,2,3,4,5,6,7,8,9,10] // These are the headers for the spreadsheet
const ouputtedArray = // these are the data cells
[
[1,2,,4,,6,,,,,]
[1,,3,,,,7,,9,10]
[1,2,,,,,,,,,]
[1,,,,,6,,8,9,]
]
电子表格本身看起来像这样
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| - | - | - | - | - | - | - | - | - | -- |
| 1 | 2 | | 4 | | 6 | | | | |
| 1 | | 3 | | | | 7 | | 9 | 10 |
| 1 | 2 | | | | | | | | |
| 1 | | | | | 6 | | 8 | 9 | |
我不知道在这里做什么,正在努力寻找解决方案。任何帮助都将是绝对惊人的!
假设
您应该能够使用以下内容:
function alignArrays(arr1, arr2) {
const result = new Array(arr1.length).fill('');
let j = 0;
for (let i = 0; i < arr1.length; i++) {
while (j < arr2.length && arr2[j] < arr1[i]) {
j++;
}
if (j < arr2.length && arr1[i] === arr2[j]) {
result[i] = arr2[j];
j++;
}
}
return result;
}
const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const array2 =
[
[1,2,4,6],
[1,3,7,9,10],
[1,2],
[1,6,8,9]
]
const alignedArray = [];
array2.forEach((arr) => alignedArray.push(alignArrays(array1, arr)))
console.log(alignedArray);