Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Gộp hai mảng, giữ lại giá trị trùng lặp chỉ một lần - JavaScript


Giả sử có hai mảng:

const arr1 = [2, 4, 5, 3, 7, 8, 9]; 
const arr2 = [1, 4, 5, 2, 3, 7, 6];

Viết hàm gộp hai mảng, loại bỏ các giá trị trùng lặp (chỉ giữ một lần).

Ví dụ

Mã thực hiện:

const arr1 = [2, 4, 5, 3, 7, 8, 9]; 
const arr2 = [1, 4, 5, 2, 3, 7, 6]; 
const mergeArrays = (first, second) => { 
  const { length: l1 } = first; 
  const { length: l2 } = second; 
  const res = []; 
  let temp = 0; 
  for(let i = 0; i < l1+l2; i++){ 
    if(i >= l1){ 
      temp = i - l1; 
      if(!res.includes(first[temp])){ 
        res.push(first[temp]); 
      }; 
    }else{ 
      temp = i; 
      if(!res.includes(second[temp])){ 
        res.push(second[temp]); 
      }; 
    }; 
  }; 
  return res; 
}; 
console.log(mergeArrays(arr1, arr2));

Kết quả

Kết quả in ra console:

[ 
  1, 4, 5, 2, 3, 7, 6, 8, 9 
]