从对象的 javascript 数组中获取前 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} ];
我们必须编写一个函数,它接受这个数组,并在另一个数组中返回该数组的前 n 个元素(前 n 个表示 duration 值最高的对象)。
因此,让我们为这个问题编写代码 −
示例
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 } ]
广告