मान लीजिए, हमारे पास इस तरह की वस्तुओं की एक सरणी है -
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 तत्व को किसी अन्य सरणी में देता है (शीर्ष का अर्थ वह वस्तु है जिसकी अवधि के लिए उच्चतम मान है)।
इसलिए, आइए इस समस्या के लिए कोड लिखें -
उदाहरण
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 } ]