假设我们有一个这样的对象数组-
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 } ]