Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

두 개의 배열에서 흔하지 않은 요소를 찾는 프로그램 - JavaScript

<시간/>

두 개의 숫자 배열이 있다고 가정해 보겠습니다. -

const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];

우리는 이러한 두 개의 배열을 취하고 두 배열에 공통적이지 않은 배열의 요소를 반환하는 JavaScript 함수를 작성해야 합니다.

이 함수의 코드를 작성해 봅시다 -

예시

다음은 코드입니다 -

const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
const unCommonArray = (first, second) => {
   const res = [];
   for(let i = 0; i < first.length; i++){
      if(second.indexOf(first[i]) === -1){
         res.push(first[i]);
      }
   };
   for(let j = 0; j < second.length; j++){
      if(first.indexOf(second[j]) === -1){
         res.push(second[j]);
      };
   };
   return res;
};
console.log(unCommonArray(arr1, arr2));

출력

다음은 콘솔의 출력입니다 -

[ 6, 5, 1 ]