다음과 같은 두 개의 객체 배열이 있다고 가정해 보겠습니다. 이 두 배열을 하나로 병합하되, name 속성 값이 중복되는 객체는 제거해야 합니다.
const first = [{
name: 'Rahul',
age: 23
}, {
name: 'Ramesh',
age: 27
}, {
name: 'Vikram',
age: 35
}, {
name: 'Harsh',
age: 34
}, {
name: 'Vijay',
age: 21
}];
const second = [{
name: 'Vijay',
age: 21
}, {
name: 'Vikky',
age: 20
}, {
name: 'Joy',
age: 26
}, {
name: 'Vijay',
age: 21
}, {
name: 'Harsh',
age: 34
}]위 예시에서 두 번째 배열에는 'Vijay'와 'Harsh'가 첫 번째 배열과 중복되며, 두 번째 배열 내부에도 'Vijay'가 반복해서 등장합니다.
combineArray 함수 정의
두 배열을 인자로 받아 하나의 새로운 배열을 반환하는 함수 combineArray를 정의해 보겠습니다. 이 함수는 내부적으로 map 객체를 해시 맵처럼 활용해 이미 등장한 name 값을 추적함으로써 중복을 효율적으로 걸러냅니다.
const combineArray = (first, second) => {
const combinedArray = [];
const map = {};
first.forEach(firstEl => {
if(!map[firstEl.name]){
map[firstEl.name] = firstEl;
combinedArray.push(firstEl);
}
});
second.forEach(secondEl => {
if(!map[secondEl.name]){
map[secondEl.name] = secondEl;
combinedArray.push(secondEl);
}
})
return combinedArray;
}
console.log(combineArray(first, second));이 함수는 단순히 두 번째 배열의 중복 항목만 제거하는 것이 아니라, 만약 첫 번째 배열 안에 중복된 항목이 존재했다면 그것 역시 함께 제거해 줍니다. 즉, 두 배열 전체에 걸쳐 name 값의 고유성을 보장합니다.
동작 원리
1. 빈 배열 combinedArray와 빈 객체 map을 생성합니다.
2. 첫 번째 배열을 순회하면서 해당 요소의 name이 map에 없으면 map에 기록하고 결과 배열에 추가합니다.
3. 두 번째 배열도 동일한 방식으로 순회하며, 이미 존재하는 name은 건너뜁니다.
4. 최종적으로 중복이 제거된 새로운 배열을 반환합니다.
객체를 조회용 맵으로 사용하면 각 요소를 O(1) 시간에 확인할 수 있어, includes()나 filter()로 매번 배열을 검색하는 방식(O(n²))보다 성능 면에서 훨씬 유리합니다.
전체 코드 예제
const first = [{
name: 'Rahul',
age: 23
}, {
name: 'Ramesh',
age: 27
}, {
name: 'Vikram',
age: 35
}, {
name: 'Harsh',
age: 34
}, {
name: 'Vijay',
age: 21
}];
const second = [{
name: 'Vijay',
age: 21
}, {
name: 'Vikky',
age: 20
}, {
name: 'Joy',
age: 26
}, {
name: 'Vijay',
age: 21
}, {
name: 'Harsh',
age: 34
}]
const combineArray = (first, second) => {
const combinedArray = [];
const map = {};
first.forEach(firstEl => {
if(!map[firstEl.name]){
map[firstEl.name] = firstEl;
combinedArray.push(firstEl);
}
});
second.forEach(secondEl => {
if(!map[secondEl.name]){
map[secondEl.name] = secondEl;
combinedArray.push(secondEl);
}
})
return combinedArray;
}
console.log(combineArray(first, second));출력 결과
콘솔 출력은 다음과 같습니다.
[
{ name: 'Rahul', age: 23 },{ name: 'Ramesh', age: 27 },{ name: 'Vikram', age: 35 },
{ name: 'Harsh', age: 34 },{ name: 'Vijay', age: 21 },{ name: 'Vikky', age: 20 },
{ name: 'Joy', age: 26 }
]결과를 보면 첫 번째 배열의 모든 고유 요소가 먼저 포함되고, 그 뒤에 두 번째 배열에서 중복되지 않은 'Vikky'와 'Joy'만 추가된 것을 확인할 수 있습니다.