다음과 같은 두 개의 객체가 있다고 가정해 보겠습니다. -
const a = {
Make: "Apple",
Model: "iPad",
hasScreen: "yes",
Review: "Great product!",
};
const b = {
Make: "Apple",
Model: "iPad",
waterResistant: false
}; 객체의 공통 속성 수를 계산하는 함수를 작성해야 하며(공통 속성이란 키와 값이 모두 동일함을 의미함) 객체 간의 유사성 비율을 나타내는 0에서 100(둘 다 포함) 사이의 숫자를 반환해야 합니다. 키/값 쌍이 일치하지 않으면 0이 되고 모두 일치하면 100이 됩니다.
유사성 비율을 계산하려면 유사한 속성의 수를 더 작은 개체(키/값 쌍이 더 작은 개체)의 속성 수로 나누고 이 결과에 100을 곱하면 됩니다.
자, 이해했다면 이제 이 함수에 대한 코드를 작성해 봅시다 -
예시
const a = {
Make: "Apple",
Model: "iPad",
hasScreen: "yes",
Review: "Great product!",
};
const b = {
Make: "Apple",
Model: "iPad",
waterResistant: false
};
const findSimilarity = (first, second) => {
const firstLength = Object.keys(first).length;
const secondLength = Object.keys(second).length;
const smaller = firstLength < secondLength ? first : second;
const greater = smaller === first ? second : first;
const count = Object.keys(smaller).reduce((acc, val) => {
if(Object.keys(greater).includes(val)){
if(greater[val] === smaller[val]){
return ++acc;
};
};
return acc;
}, 0);
return (count / Math.min(firstLength, secondLength)) * 100;
};
console.log(findSimilarity(a, b)); 출력
콘솔의 출력은 다음과 같습니다. -
66.66666666666666
더 작은 개체에는 3개의 속성이 있고 그 중 2개의 공통 속성은 약 66%에 달하기 때문입니다.