Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
Merge Arrays With Only Elements in Both (Efficiently)

I have some working code, though it seems like it should be much more efficient. I feel there are too many filters working through the same data sets. Is there a cleaner or more efficient way of merging 2 arrays without duplicating?

const x = [1,3,7,4,9];
const y = [2,3,9,13,4];

const yFilteredByX = y.filter(element => x.includes(element));
const xFilteredByY = x.filter(element => y.includes(element));

const unique = (value, index, self) => {
    return self.indexOf(value) === index;
};

const newArr = yFilteredByX.concat(xFilteredByY);
const uniqueArr = newArr.filter(unique);

console.log(uniqueArr);

Currently outputs [3,9,4] successfully.

I made a quick fiddle

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

  • Create a Set for each array
  • Iterate over the items of the first using Array#filter and return only those in the second set

const _getCommonElements = (arr1 = [], arr2 = []) => {
  const set1 = new Set(arr1), set2 = new Set(arr2);
  return [...set1].filter(e => set2.has(e));
}

console.log( _getCommonElements([1,3,7,4,9], [2,3,9,13,4]) );

about 4 years ago · Juan Pablo Isaza Report

0

Create a Set from one, and then filter the other by checking if the set has elements.

const x = [1, 3, 7, 4, 9];
const y = [2, 3, 9, 13, 4];

const uniqueInX = new Set(x);
const uniqueInBoth = y.filter(e => uniqueInX.has(e));

console.log(uniqueInBoth);

about 4 years ago · Juan Pablo Isaza Report

0

It seems like you intend to calculate the intersection of two sets, thus the corresponding function operation from the mozilla developer docs can be used, e.g.

const x = [1, 3, 7, 4, 9];
const y = [2, 3, 9, 13, 4];

function intersection(setA, setB) {
  let _intersection = new Set()
  for (let elem of setB) {
    if (setA.has(elem)) {
      _intersection.add(elem)
    }
  }
  return _intersection
}

const setX = new Set(x);
const setY = new Set(y);

const commonSet = intersection(setX, setY);

console.log(...commonSet); // [3, 9, 4]

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!