สมมติว่าเรามีอาร์เรย์ของวัตถุเช่นนี้ −
ตัวอย่าง
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 ตัวที่มีค่าสตริงที่ยาวที่สุดสำหรับคีย์ข้อความ และอ็อบเจ็กต์ทั้งหมดควรมีค่าที่ไม่ซ้ำกันสำหรับคีย์ข้อความ หากไม่มีอ็อบเจ็กต์ที่ไม่ซ้ำกัน เราควรส่งคืนอ็อบเจ็กต์ที่ไม่ซ้ำทั้งหมด
ดังนั้น เรามาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
ตัวอย่าง
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' }
]