สมมติว่าเรามีอาร์เรย์ของวัตถุเช่นนี้ −
const arr = [ {"id":0,"start":0,"duration":117,"slide":4,"view":0}, {"id":0,"start":0,"duration":12,"slide":1,"view":0}, {"id":0,"start":0,"duration":41,"slide":2,"view":0}, {"id":0,"start":0,"duration":29,"slide":3,"view":0}, {"id":0,"start":0,"duration":123,"slide":3,"view":0}, {"id":0,"start":0,"duration":417,"slide":2,"view":0}, {"id":0,"start":0,"duration":12,"slide":1,"view":0}, {"id":0,"start":0,"duration":67,"slide":2,"view":0} ];
เราต้องเขียนฟังก์ชันที่ใช้อาร์เรย์นี้และส่งกลับองค์ประกอบ n ด้านบนของอาร์เรย์ในอาร์เรย์อื่น (top หมายถึงออบเจ็กต์ที่มีค่าระยะเวลาสูงสุด)
ดังนั้น เรามาเขียนโค้ดสำหรับปัญหานี้กันเถอะ -
ตัวอย่าง
const arr = [ {"id":0,"start":0,"duration":117,"slide":4,"view":0}, {"id":0,"start":0,"duration":12,"slide":1,"view":0}, {"id":0,"start":0,"duration":41,"slide":2,"view":0}, {"id":0,"start":0,"duration":29,"slide":3,"view":0}, {"id":0,"start":0,"duration":123,"slide":3,"view":0}, {"id":0,"start":0,"duration":417,"slide":2,"view":0}, {"id":0,"start":0,"duration":12,"slide":1,"view":0}, {"id":0,"start":0,"duration":67,"slide":2,"view":0} ]; const topN = (arr, n) => { if(n > arr.length){ return false; } return arr .slice() .sort((a, b) => { return b.duration - a.duration }) .slice(0, n); }; console.log(topN(arr, 3)); console.log(topN(arr, 4)); console.log(topN(arr, 5));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น -
[ { id: 0, start: 0, duration: 417, slide: 2, view: 0 }, { id: 0, start: 0, duration: 123, slide: 3, view: 0 }, { id: 0, start: 0, duration: 117, slide: 4, view: 0 } ] [ { id: 0, start: 0, duration: 417, slide: 2, view: 0 }, { id: 0, start: 0, duration: 123, slide: 3, view: 0 }, { id: 0, start: 0, duration: 117, slide: 4, view: 0 }, { id: 0, start: 0, duration: 67, slide: 2, view: 0 } ] [ { id: 0, start: 0, duration: 417, slide: 2, view: 0 }, { id: 0, start: 0, duration: 123, slide: 3, view: 0 }, { id: 0, start: 0, duration: 117, slide: 4, view: 0 }, { id: 0, start: 0, duration: 67, slide: 2, view: 0 }, { id: 0, start: 0, duration: 41, slide: 2, view: 0 } ]