简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM