Tomas
Tomas

Reputation: 129

Search array in array

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? :)

Upvotes: 0

Views: 60

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386550

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; }

Upvotes: 1

Related Questions