I am trying to merge two arrays on columns with similar data
I can get this to work if both arrays have the same length dimension, but how can I generalize my function to work if arrays have different lengths?
where either arrA or arrB could have the greater length
Thank you
what I get
[ [ 'age', 'AAA', 'name' ],
[ 25, 'aaa', 'Alice' ],
[ 30, 'bbb', 'Bob' ] ]
what I want
[
[ 'age', 'AAA', 'name' ],
[ 25, 'aaa', 'Alice' ],
[ 30, 'bbb', 'Bob' ],
[ 60, 'zzz', '' ]
]
function mergeRowsLOOP_n() {
const arrB = [
["id", "name"],
[1, "Alice"],
[2, "Bob"],
];
const arrA = [
["age", "ID", "AAA"],
[25, 1, "aaa"],
[30, 2, "bbb"],
[60, 5, "zzz"]
];
let X = mergeRowsLOOP(arrA, arrB, "ID", "id");
console.log(X)
}
//a= array1, b=array2
//aKey = Header for Matching of arra1, bKey = Header for Matching of arra2
//bColumns indices of postback columns of array2; bColumns=[] to postback ALL array2 columns
function mergeRowsLOOP(a, b, aKey, bKey, bColumns = []) {
const bIdx = b[0].findIndex(s => s.toLowerCase() === bKey.toLowerCase());
bColumns = (bColumns.length === 0) ? b : getColumns(b, [bIdx, ...bColumns]);
const aIdx = a[0].findIndex(s => s.toLowerCase() === aKey.toLowerCase()),
bColumnsIdx = bColumns[0].findIndex(s => s.toLowerCase() === bKey.toLowerCase()),
mergedArray = [];
console.log(bColumnsIdx)
for (let rowA of a) {
for (let rowB of bColumns) {
if (rowA[aIdx].toString().toLowerCase() === rowB[bColumnsIdx].toString().toLowerCase()) {
rowA = spliceNthPos(rowA, aIdx);
rowB = spliceNthPos(rowB, bColumnsIdx);
mergedArray.push(rowA.concat(rowB, ));
}
}
};
return mergedArray;
}
function spliceNthPos(row, n) {
let i = row.length;
while (i--) {
i === n && row.splice(i, 1);
}
return row;
}
2
Answers
I believe your goal is as follows.
You want to achieve the following conversion.
From
To
In this case, how about the following sample script?
Sample script:
When the processes of
arrB
andarrA
are separeted, it becomes as follows.When this script is run, the following result is obtained.
References:
An approach with an object and an array for empty columns.