在遍历两个数组时查找公用值

Ade*_*emo 5 javascript arrays

我有一种情况需要比较和查找两个数组的共同值。我很清楚如何做到这一点,但不确定在这种情况下如何做到这一点。

我的第一个数组如下所示:

[ { kind: 'E',
    path: [ 'short_name' ],
    lhs: 'testing',
    rhs: 'testing1' },
  { kind: 'E',
    path: [ 'agent_name' ],
    lhs: 'testing',
    rhs: 'testing2' } ]
Run Code Online (Sandbox Code Playgroud)

上面的数组代表与文档更改有关的信息。

我的第二个数组如下所示:

[ { lhs: 'legacyId', rhs: 'id_number' },
  { lhs: 'name.short', rhs: 'short_name' },
  { lhs: 'name.long', rhs: 'agent_name' },
  { lhs: 'gender', rhs: 'gender' },
  { lhs: 'dob', rhs: 'date_of_birth' } ]
Run Code Online (Sandbox Code Playgroud)

我需要做的是遍历并在第一个数组的元素和第二个数组的“ rhs”值中找到“ path”的通用值。

因此,根据此处的示例,我应该最终找到以下值:short_nameagent_name

我如何编写一个循环在两个数组上执行此操作?

Kob*_*obe 6

您可以reduce使用第一个数组,并forEach在第二个数组上使用循环,以查看每个值是否相等,然后将值推入累加器:

const arr1 = [{ kind: 'E', path: [ 'short_name' ], lhs: 'testing', rhs: 'testing1' }, { kind: 'E', path: [ 'agent_name' ], lhs: 'testing', rhs: 'testing2' }]
const arr2 = [{ lhs: 'legacyId', rhs: 'id_number' }, { lhs: 'name.short', rhs: 'short_name' }, { lhs: 'name.long', rhs: 'agent_name' }, { lhs: 'gender', rhs: 'gender' }, { lhs: 'dob', rhs: 'date_of_birth' }]

const common = arr1.reduce((a, o1) => {
  const match = arr2.find(o2 => o1.path[0] === o2.rhs)
  match && a.push(match.rhs)
  return a
}, [])

console.log(common)
Run Code Online (Sandbox Code Playgroud)

如果您确实希望这样做,可以在一行中使用查找而不是第二个reduce来编写:

const a = [{ kind: 'E', path: [ 'short_name' ], lhs: 'testing', rhs: 'testing1' }, { kind: 'E', path: [ 'agent_name' ], lhs: 'testing', rhs: 'testing2' }]
const b = [{ lhs: 'legacyId', rhs: 'id_number' }, { lhs: 'name.short', rhs: 'short_name' }, { lhs: 'name.long', rhs: 'agent_name' }, { lhs: 'gender', rhs: 'gender' }, { lhs: 'dob', rhs: 'date_of_birth' }]

const common = a.reduce((a, o1) => (a.push(b.find(o2 => o1.path[0] === o2.rhs).rhs), a), [])

console.log(common)
Run Code Online (Sandbox Code Playgroud)

或者,对于更高性能的解决方案;)您可以使用一组:

const a = [{ kind: 'E', path: [ 'short_name' ], lhs: 'testing', rhs: 'testing1' }, { kind: 'E', path: [ 'agent_name' ], lhs: 'testing', rhs: 'testing2' }]
const b = [{ lhs: 'legacyId', rhs: 'id_number' }, { lhs: 'name.short', rhs: 'short_name' }, { lhs: 'name.long', rhs: 'agent_name' }, { lhs: 'gender', rhs: 'gender' }, { lhs: 'dob', rhs: 'date_of_birth' }]
var commonValues = []
var set = new Set([])

for (let i = 0; i < a.length; i++) { 
  const value = a[i].path[0]
  if (!set.has(value)) set.add(value)
}
for (let i = 0; i < b.length; i++) {
  const val = b[i].rhs
  if (set.has(val)) commonValues.push(val)
}

console.log(commonValues)
Run Code Online (Sandbox Code Playgroud)