This is mostly for academic interest, as I've managed to solve it an entirely different way, but, short story, what I want is, in pseudocode:
Foreach object in array1
Find matching otherObject in array2 // must exist and there's only 1
Find matching record in array3 // must exist and there's only 1
If record.status !== otherObject.status
push { otherObject.id, record.status } onto newArray
It intuitively seems to me there should be a way to do something with array1.filter(<some function>).map(<some other function>
, but I can't get it to work in practice.
Here's a real-world example. This works:
function update(records) {
const filtered = records.filter((mcr) => {
const match = at._people.find((atr) => atr.email.toLowerCase() ===
mcr.email.toLowerCase());
return (match.subscriberStatus.toLowerCase() !==
mc.mailingList.find((listEntry) =>
listEntry.id === mcr.id).status.toLowerCase()
);
});
const toUpdate = filtered.map((mcr) => {
const match = at._people.find((atr) => atr.email.toLowerCase() ===
mcr.email.toLowerCase());
return ({ 'id': match.id,
'fields': {'Mailing List Status': mcr.subscriberStatus }
}
);
});
}
But what bums me out is the duplicated const match =
. It seems to me that those could be expensive if at._people
is a large array.
I naively tried:
function update(records) {
let match;
const toUpdate = records.filter((mcr) => {
match = at._people.find((atr) => atr.email.toLowerCase() ===
mcr.email.toLowerCase());
// return isDifferent?
return (match.subscriberStatus.toLowerCase() !==
mc.mailingList.find((listEntry) => listEntry.id === mcr.id).status.toLowerCase());
}).map((foundMcr) => {
return ({ 'id': match.id, 'fields': {'Mailing List Status': foundMcr.subscriberStatus } })
});
}
But (somewhat obviously, in retrospect) this doesn't work, because inside the map
, match
never changes — it's just always the last thing it was in the filter
. Any thoughts on how to pass that match.id
found in the filter
on an entry-by-entry basis to the chained map
? Or, really, any other way to accomplish this same thing?