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