다음과 같은 객체 배열이 있습니다. 속성 이름에 중복 값이 있는 객체를 제거하는 하나로 병합해야 합니다. -
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
}, ] 우리는 CombineArray 함수를 정의하고 인수로 결합할 두 개의 배열을 가져와서 새 배열을 반환합니다 -
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)); 이 기능은 두 번째 배열에서 중복 항목을 제거할 뿐만 아니라 첫 번째 배열에 중복 항목이 있었다면 해당 항목도 제거했을 것입니다.
전체 코드는 다음과 같습니다 -
예시
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 }
]