I’ve have seen some answers to similar questions, but I haven’t seen one touching multiple conditions and I couldn’t adapt any to this need.
Basically, ar1 should have its labels replaced by the urls.
Here is the function beating me:
let ar1 = [
["Client", "Date", "Label1", "Label2"],
["A", "11/15/2022", "Label1", "Label2"],
["B", "11/15/2022", "Label1", "Label2"],
["C", "11/15/2022", "Label1", "Label2"]
];
const label1Col = ar1[0].indexOf('Label1')
const label2Col = ar1[0].indexOf('Label2')
let ar2 = [
["Client", "Date", "Label2", "Label1",],
["A", "11/15/2022", "www.elonscrewing.com", "www.google.com"],
["B", "11/15/2022", "www.elonscrewing.com", "www.google.com"],
["C", "11/15/2022", "www.elonscrewing.com", "www.google.com"]
]
const ar2label1Col = ar2[0].indexOf('Label1')
const ar2label2Col = ar2[0].indexOf('Label2')
ar1.forEach(function(val) {
ar2.forEach(function(link) {
val[label1Col] = link[ar2label1Col];
val[label2Col] = link[ar2label2Col];
})
})
console.log(ar1)
Appreciate any help!
>Solution :
For unordered arrays (/arrays with different orders) just check with an if condition if Date and Client are equal (and string the conditions with &&s together) – see code below:
but at that point you should really think about, if arrays are still the data type you want to work with. This would be way easier with objects (so if you do similar operations a lot, maybe consider converting your arrays to objects (makes life way easier, and code more readable)
let ar1 = [
["Client", "Date", "Label1", "Label2"],
["B", "11/15/2022", "Label1", "Label2"],
["A", "11/15/2022", "Label1", "Label2"],
["C", "11/15/2022", "Label1", "Label2"]
];
const label1Col = ar1[0].indexOf('Label1')
const label2Col = ar1[0].indexOf('Label2')
const dateIdx = ar1[0].indexOf('Date')
const clientIdx = ar1[0].indexOf('Client')
let ar2 = [
["Client", "Date", "Label2", "Label1",],
["A", "11/15/2022", "www.aaaaaaaaaaa.com", "www.google.com"],
["B", "11/15/2022", "www.bbbbbbbbbb.com", "www.google.com"],
["C", "11/15/2022", "www.elonscrewing.com", "www.google.com"]
]
const ar2label1Col = ar2[0].indexOf('Label1')
const ar2label2Col = ar2[0].indexOf('Label2')
const ar2ClientIdx = ar2[0].indexOf('Client')
const ar2DateIdx = ar2[0].indexOf('Date')
ar1.forEach(function(val) {
ar2.forEach(function(link) {
if (val[clientIdx] === link[ar2ClientIdx] && val[dateIdx] === link[ar2DateIdx]) {
val[label1Col] = link[ar2label1Col];
val[label2Col] = link[ar2label2Col];
}
})
})
console.log(ar1)