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

96
Views
Compare two arrays and push same element in one array and rest in other array in javascript

Compare two arrays and push same element in one array and rest in other array in javascript

const arr1 = ['a', 'c', 'e', 'j', 'p', 'r', 'l'];

const arr2 = ['e', 'r'];

**Expected response :**

Same elements ['e', 'r']
different elements ['a', 'c', 'j', 'l']

expected array : ['ac', 'e', 'jp', 'r', 'l']

I have tried this is it correct way ?

const res = [];
  let txt = '';

  for (let i = 0; i < arr1.length; i++) {
    for (let j = 0; j < arr2.length; j++) {
      if (arr1[i] === arr2[j]) {
        res.push(txt);
        res.push(arr2[j]);
        j += 1;
        txt = '';
      } else if (j === arr2.length - 1) {
        txt += `${arr1[i]} `;
        if (i === arr1.length - 1) {
          res.push(txt);
        }
      }
    }
  }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

By observing your expected array and your own code segment I could guess what you are trying to achieve (It's not full clear from your problem statement). If my understanding is correct then your code might not result in expected answer in all cases if the input array is not fixed. I have modified your code as below. Have a check. set arr2 input as ['e', 'r', 't'] , or ['a', 'c', 'e', 'j', 'p', 'r', 'l'] and check the output. Let me know if it's helpful.

for (let i = 0; i < arr1.length; i++) {
    for (let j = 0; j < arr2.length; j++) {
      if (arr1[i] === arr2[j]) {
        if(txt!=='') res.push(txt)
        res.push(arr2[j]);
        txt = '';
        break;
      } 
      else if (j === arr2.length - 1) {
        txt+= txt===''?`${arr1[i]}` : ` ${arr1[i]}`
        if (i === arr1.length - 1) {
          res.push(txt);
        }
      }
    }
 }
about 4 years ago · Juan Pablo Isaza Report

0

To group the elements by same and different you can just use filter.

const arr1 = ['a', 'c', 'e', 'j', 'p', 'r', 'l'];
const arr2 = ['e', 'r'];

const sameElements = [...arr1].filter(x => arr2.includes(x))
const differentElements = [...arr1].filter(x => !arr2.includes(x))

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!