Skip to content
Advertisement

Find common elements from arrays’s which are inside an Object – Javascript

So I have an Object that contains multiple arrays

x = {
    c: ['Full_Name', 'Last_Name', 'Email', 'Organizations', 'MISC', 'UNIQUEID']
    small: ['Title', 'Organizations', 'URL', 'UNIQUEID']
    .
    .
    .}

What is the best and the fastest way to find all the similar elements from all these arrays?

So for example in this case the answer will be ['Organization', 'UNIQUEID']

Advertisement

Answer

a possible approach using reduce and Set. for the accumulator I’m initializing it with the first array (x.c). Doesn’t matter which one since in the end we are taking intersection anyway. Inside the reduce I’m intersecting the accumulator with the current iteration array

const x = {
  c: ['Full_Name', 'Last_Name', 'Email', 'Organizations', 'MISC', 'UNIQUEID'],
  small: ['Title', 'Organizations', 'URL', 'UNIQUEID'],
  big: ['abc', 'Organizations', 'def', 'UNIQUEID']
}


const res = Object.values(x).reduce((acc, curr) => {
  return new Set(curr.filter(i => acc.has(i)))
}, new Set(x.c))

console.log([...res])

almost similar with a for loop except I’m skipping first element in loop

const x = {
  c: ['Full_Name', 'Last_Name', 'Email', 'Organizations', 'MISC', 'UNIQUEID'],
  small: ['Title', 'Organizations', 'URL', 'UNIQUEID'],
  big: ['abc', 'Organizations', 'def', 'UNIQUEID']
}

const values = Object.values(x)
let acc = new Set(values[0])
for (let i = 1; i < values.length; i++) {
  acc = new Set(values[i].filter(j => acc.has(j)))
}

console.log([...acc])
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement