I'm running a test each day that goes to a page and reads some data. Oldest info are put to the end of the array, newest at the beginning. There will be situations when some entries are removed from the page and some are added. But still the order will be the same - older at the end, newer at the beginning.
After each run, when data is taken I need to compare it with the entry in db. The output should be like: [entries_existing_only_in_new_run, entries_from_old_run_but_existing_also_in_new_run]. Maybe example will be better :D
Have two arrays:
const new = [
{
role: 'dev',
some: 'new'
},
{
role: 'dev',
some: 'new'
},
{
role: 'dev',
some: 'new'
},
{
role: 'qa',
some: 'new'
},
{
role: 'sm',
some: 'new'
},
]
const old = [
{
role: 'dev',
some: 'old'
},
{
role: 'qa',
some: 'old'
},
{
role: 'sm',
some: 'old'
},
{
role: 'tl',
some: 'old'
},
]
The point here is to compare role from those two arrays, take beginning of the new one (that is missing in the old one) and the rest from the old one. As tl role is missing in the new entry it should not be added. So the output should be
const modified = [
{
role: 'dev',
some: 'new'
},
{
role: 'dev',
some: 'new'
},
{
role: 'dev',
some: 'old'
},
{
role: 'qa',
some: 'old'
},
{
role: 'sm',
some: 'old'
},
]
How to do it? :)
-
3What you've tried so far ? can you please post the codeCode Maniac– Code Maniac2021年04月06日 11:35:27 +00:00Commented Apr 6, 2021 at 11:35
-
@CodeManiac, to be honest I have no idea how to do it. Was thinking about it a lot but just don't know. Know how to put it in words, but don't how to write it in JS :) The problem for me is that for each new entry I need to compare the rest of the new array with old array, if roles are the same. But don't know how to do it if, let's say, 3rd entry+ will be the same. How to compare is 3rd from new === 1st from old, 4th from new === 2nd from old, etc.Tomas– Tomas2021年04月06日 11:44:06 +00:00Commented Apr 6, 2021 at 11:44
1 Answer 1
You could group the old ones by their role and iterate the new ones from the end and replace with new ones.
const
newArray = [{ role: 'dev', some: 'new' }, { role: 'dev', some: 'new' }, { role: 'dev', some: 'new' }, { role: 'qa', some: 'new' }, { role: 'sm', some: 'new' }],
oldArray = [{ role: 'dev', some: 'old' }, { role: 'qa', some: 'old' }, { role: 'sm', ome: 'old' }, { role: 'tl', some: 'old' }],
olds = oldArray.reduce((r, o) => {
(r[o.role] = r[o.role] || []).push(o);
return r;
}, {}),
result = newArray.reduceRight((r, o) => {
r.unshift((olds[o.role] || []).shift() || o);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
2 Comments
TypeError: olds[o.role] is undefined.??= with a more common logical OR ||.