다음과 같은 객체 배열이 있다고 가정해 보겠습니다. -
예시
const arr = [
{text:'use'},
{text: 'secur'},
{text: 'form'},
{text: 'user'},
{text: 'users'},
{text: 'form'},
{text: 'secur'},
{text: 'sec'},
{text: 'users'},
{text: 'secu'},
{text: 'secur'},
{text: 'for'},
{text: 'form'}
] 우리의 임무는 이 배열과 숫자 n을 받는 함수를 작성하는 것입니다. 이 함수는 텍스트 키에 대해 가장 긴 문자열 값을 가진 n개 개체의 배열을 반환해야 하며 모든 개체는 텍스트 키에 대해 고유한 값을 가져야 합니다. n개의 고유한 개체가 없으면 모든 고유한 개체를 반환해야 합니다.
따라서 이 함수의 코드를 작성해 보겠습니다 -
예시
const arr = [
{text: 'use'},
{text: 'secur'},
{text: 'form'},
{text: 'user'},
{text: 'users'},
{text: 'form'},
{text: 'secur'},
{text: 'sec'},
{text: 'users'},
{text: 'secu'},
{text: 'secur'},
{text: 'for'},
{text: 'form'}
];
const sorter = (a, b) => {
return b.text.length - a.text.length;
}
const longestUnique = (arr, num) => {
const copy = arr.slice();
copy.sort(sorter);
const map = new Map();
const uniqueCopy = copy.filter(el => {
const exists = map.get(el.text);
if(exists){
return false;
};
map.set(el.text, 1);
return true;
});
return uniqueCopy.splice(0, num);
}
console.log(longestUnique(arr, 4));
console.log(longestUnique(arr, 12)); 출력
콘솔의 출력은 -
[
{ text: 'secur' },
{ text: 'users' },
{ text: 'form' },
{ text: 'user' }
]
[
{ text: 'secur' },
{ text: 'users' },
{ text: 'form' },
{ text: 'user' },
{ text: 'secu' },
{ text: 'use' },
{ text: 'sec' },
{ text: 'for' }
]